In this guide we will be covering some JavaScript features,
and how they are used in Ember applications.

Variable declarations

A variable declaration, also called binding, is when you assign a value to a variable name.
An example of declaring a variable containing the number 42 is like so:

var myNumber = 42;

JavaScript initially had two ways to declare variables, globally and var.
With the release of ES2015, const and let were introduced.
We will go through the different ways to declare a variable,
also called bindings because they bind a value to a variable name,
and why modern JavaScript tends to prefer const and let.

var

Variable declarations using var exist in the entire body of the function where they are declared.
This is called function-scoping, the existence of the var is scoped to the function.
If you try to access a var outside of the function it is declared,
you will get an error that the variable is not defined.

For our example, we will declare a var named name.
We will try to access it both inside the function and outside,
and see the results we get:

In the previous example, we can see that the first console.log(name) prints out undefined instead of the value.
That is because of a feature of JavaScript called hoisting.
Any variable declaration is moved by the programming language to the top of the scope it belongs to.
As we saw at the beginning, var is scoped to the function,
so the previous example is the same as:

const and let

There are two major differences between var and both const and let.
const and let are both block-level declarations, and they are not hoisted.

Because of this they are not accessible outside of the given block scope (meaning in a function or in {}) they are declared in.
You can also not access them before they are declared, or you will get a ReferenceError.

console.log(name) // ReferenceError: name is not defined
if (person) {
console.log(name) // ReferenceError: name is not defined
let name = 'Gob Bluth'; // "Gob Bluth"
} else {
console.log(name) // ReferenceError: name is not defined
}

const declarations have an additional restriction, they are constant references,
they always refer to the same thing.
To use a const declaration you have to specify the value it refers,
and you cannot change what the declaration refers to: