var is declared as a function-scope or globally scoped variable and can be declared as undefined, or with a predetermined value.
In the code below, x is never defined and console.log(x) will throw an error.
In the code below, x is defined after console.log(x), and due to hoisting, console.log(x) will not throw an error. Instead, it will return undefined.
Taking this a step further, consider the code below. The localScope and i variables are initialized as 0. The for-loop iterates from 0 to 9 and adds i to the localScope variable. After the for-loop is complete, both localScope and i are returned. In this example, localScope returns 45 and i returns 10. i evaluates to 10 because var is NOT block-scoped. This can lead to unpredictable behavior.
let declares a blocked scope variable, and similar to var, can be declared as undefined or with an initial value. The let variable is limited to the scope of the block it is defined.
In contrast to var, let variables must be declared before usage as let declarations are not hoisted.
In the code below, y is never defined and console.log(y) will throw an error.
In the code below, y is defined after console.log(y) and an error will be thrown because variables declared with let are not processed before code execution.
let is block-scoped and in the example below, console.log(i) will throw an error. Variable i is only available within the for-loop.
const declares a read-only variable meaning its value cannot be changed; however, if const is declared as an object or array its properties can be updated. The const variables must be declared with a value and are block-scoped variables. The const variable cannot be redeclared within the same scope, and const is not hoisted.
The code below shows the variable z being declared with the value 100. z cannot be changed within the scope it is defined.
In the code below, const is used to declare an object with the property ‘key’. The object is represented as the variable obj.
If obj is redeclared in the same scope, an error will be thrown.
Working with the object’s properties is allowed, and the properties can be manipulated as follows.
As shown, variables can be declared with: var, const, and let. Variables declared with var are hoisted and processed before code execution. Both let and const are block scope declarations and must be defined within the scope prior to use.