1The let statement declares a block scope local variable, optionally initializing it to a value.
2
3let x = 1;
4
5if (x === 1) {
6 let x = 2;
7
8 console.log(x);
9 // expected output: 2
10}
11
12console.log(x);
13// expected output: 1
1// var is function-scoped, so redeclaring it in a block will cause its value outside the block to change as well:
2
3var one = 'one: declared outside the block';
4
5if (true === true) {
6 var one = 'one: declared inside the block'; // notice: we redeclare 'one' here
7 console.log(one); // prints 'one: declared inside the block'
8}
9
10console.log(one); // also prints 'one: declared inside the block', because the variable was redeclared in the 'if' block. The outer 'var' variable was therefore destroyed and replaced by inner var variable.
11
12// 'let' is block-scoped, so redeclaring a 'let' variable inside of a block creates a different 'let' variable with the same name whose scope is inside the block:
13
14let two = 'two: declared outside the block';
15
16if (true === true) {
17 let two = 'two: declared inside the block';
18 console.log(two); // prints 'two: declared inside the block'
19}
20
21console.log(two); // prints 'two: declared outside the block', because two declared inside the block is a separate variable. The 'let' variables are unrelated and therefore are unaffected by each other.
1/* DIFFERENCE BETWEEN LET AND VAR */
2
3//LET EXAMPLE
4{
5 let a = 123;
6};
7
8console.log(a); // undefined
9
10//VAR EXAMPLE
11{
12 var a = 123;
13};
14
15console.log(a); // 123