Skip to content

JavaScript let keyword

In this tutorial I will introduce you to new ECMAScript 6 let keyword. Variables declared with let keyword behave like other languages variables. These variables are unlike to the variables which are declared with var keyword. Let me show you example…

let

Variables which are declared with let statement are block scoped local variables which means they are limited in scope to the block, statement, or expression on which it is used. You can optionally initialize variables with value. This is unlike the var statement, which defines a variable globally, or locally to an entire function regardless of block scope.

Variables which are defined or declared with let keyword are not bind to window object.

let x = 10; 
console.log(x); // 10
console.log(window.x); // undefined
var y = 20;
console.log(x); // 20
console.log(window.x); // 20

Example with var and let

    var x = 100;

    for(var i =0; i<3; i++){
        var x = i * 2;
        console.log(x);
    }

    console.log('this is the final value of x', x);

Running the above code produces the wrong results, it changes the outer x from 100 to 4 after the loop, as you can see from this output:

0
2
4
this is the final value of x 4

Now replace all the occurrences of var with let. Don’t change anything else yet.

    let x = 100;

    for(var i =0; i<3; i++){
        let x = i * 2;
        console.log(x);
    }

    console.log('this is the final value of x', x);

Now we are seeing correct output. This is because unlike var variables which are function-scoped, let variables are block-scoped. they only exist in the block they are defined in.

0
2
4
this is the final value of x 100
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments