Close

JavaScript - Block scoping with let And const

[Last Updated: Jul 23, 2018]

ES6 introduced two new keywords let and const which provide different scoping than var variables.

let

It is blocked-scoped i.e it only exits within any kind of the curly bracket block.

const

It is also blocked-scoped but must be initialized with declaration.
Also its value cannot be changed.

var (pre-existing scoping)

Not blocked-scoped. They scoped to either the containing function (if defined inside a function - also referred as local-scoped) or the whole script (if defined outside a function - referred as global-scoped).

Examples

Using let

Block visibility

Variables defined inside a block using 'let' are not visible outside.

{
    let x = 3;
}
console.log(x);

Whereas variables defined inside a block using 'var' are visible outside.

{
    var x = 3;
}
console.log(x);

No overriding

Variables defined with 'let' do not override external variables.

var x = 2; //or let x =2;
if (x > 1) {
    let x = 3;
    console.log(x);
}
console.log(x);

Variables defined with 'var' override external variables.

var x = 2;
if (x > 1) {
    var x = 3;
    console.log(x);
}
console.log(x);

As global variables

Variables defined outside a block using 'let' are visible inside blocks/functions.

let x = 3;

function increment() {
    x++;
}
console.log(x);
increment();
console.log(x);

No hoisting

'let' does not allow variable hoisting (variable hoisting is assigning values to variables before declaring them).

x = 2;
let x;
console.log(x);

Whereas 'var' allows variable hoisting:

x = 2;
var x;
console.log(x);

Using const

The variables used with 'const' must be initialized at declaration:

const x = 5;
console.log(x);
const x;
x = 5;

Like 'let' variables, 'const' variables are also blocked scope.

{
    const x = 3;
}
console.log(x);

See Also