let & const

Visakh Vijayan - Jan 16 '19 - - Dev Community

ES6 introduced two new alternatives to var keyword namely let and const.

var allows you to define the same variable over and over again without any errors.

var x = 10;
var x = 10; // Doesn't throw up an error

console.log(x);
Enter fullscreen mode Exit fullscreen mode

This might lead to accidentaly changing the values of a variable.

However, this is not the case with let. If you try to do the same thing with let, it will throw up an error.

let x = 10;
let x = 10; // Duplicate declaration error.

console.log(x);
Enter fullscreen mode Exit fullscreen mode

const on the other hand is used when you want to create variable that won't change it's value ever.

const x = 10;
x = 12; // Cannot reassign ever.

console.log(x);
Enter fullscreen mode Exit fullscreen mode

Function and Block scoping

While var,let and const have function level scoping, let and const go a step further. They allow block level scoping too.


var x = 10;
let x1 = 10;

if (1)
{
   var y = 10;
   let y1 = 10;
}

console.log(y); // Y is available over here.
console.log(y1); // Y is not available over here.

Enter fullscreen mode Exit fullscreen mode

Next: Coming soon

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .