Javascript variable declarations ‘let’ and ‘const’

The release of Javascript ES6 brings two new ways to declare variables: let and const. In time, these will come to replace the current method of using var. What’s so special about these two new ways you ask? With let, variable scoping is contained to only the nearest enclosing block. Also, the variable is only visible in that block. For example

function foo(){
console.log(i); //undefined, i is not visible here
for(let i = 0; i < 3; i++){
console.log(i); //0, 1, 2
}
console.log(i); //undefined, i is not visible here
}

Compare this to the use of var

function bar(){
console.log(i); //undefined, but i is visible here
for(var i = 0; i < 3; i++){
console.log(i); //0, 1, 2
}
console.log(i); //3
}

Another example of the use of let is

function biz(){
let x = 5;
if(true){
let y = 2;
console.log(x); //5
}
console.log(y); //undefined
}

The reason x is defined in the above example is because the if block is contained within the scope of the biz function. We also see that y is undefined. Following our logic above, we see this is because the function biz is not contained within the scope of the if block.

With const, the variable is declared only once and can not be changed; it becomes read-only. For example

const x = 5;
console.log(x); //5
x = 2; //error, x is read only

These new variable declaration methods give much more control over the way we define and use variables in Javascript, and I am very much looking forward to diving into them.