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
1let a = 'hello'; // globally scoped
2var b = 'world'; // globally scoped
3console.log(window.a); // undefined
4console.log(window.b); // 'world'
5var a = 'hello';
6var a = 'world'; // No problem, 'hello' is replaced.
7let b = 'hello';
8let b = 'world'; // SyntaxError: Identifier 'b' has already been declared
1function run() {
2 var foo = "Foo";
3 let bar = "Bar";
4
5 console.log(foo, bar);
6
7 {
8 let baz = "Bazz";
9 console.log(baz);
10 }
11
12 console.log(baz); // ReferenceError
13}
14
15run();
1/*
2
3Therefore,
4
5 var:
6 -can be declared outside any function to be used inside any function
7 -can be declared inside any function or any other {} which are of only if or if-else or switch etc. and can be used anywhere inside the function
8 -can be changed again and again anywhere
9 let:
10 -can be declared outside any function to be used inside any function
11 -if declared inside any function or any other {} which are of only if or if-else or switch etc. and can't be used anywhere inside the function and can be only used inside statement
12 - can be changed again and again only inside the statement in which they are made in
13 const:
14 -can be declared outside any function to be used inside any function
15 -can be declared inside any function or any other {} which are of only if or if-else or switch etc. and can be used anywhere inside the function
16 -cannot be changed again and agan anywhere, if tried to, will result in an error
17
18*/
19// var has function scope. (this variable can be accssed from anywhere inside function)
20// let & const has block scope.(this variable can not be accessed out of block. means outside of if else but inside of a function it can not be accessed. only inside that block we can access this variable)
21// https://www.youtube.com/watch?v=--Vh17ocC_s
22function func(){
23 if(true){
24 var A = 1;
25 let B = 2;
26 }
27 A++; // 2 --> ok, inside function scope
28 B++; // B is not defined --> not ok, outside of block scope
29 return A + B; // NaN --> B is not defined
30}
31//example 2
32var variable1 // declared using var
33const variable2 // declared using const
34
35myFunction1();
36
37function myFunction1() {
38 variable1 = "hello!";
39 console.log(variable1);
40 // "hello!"
41}
42
43myFunction2();
44
45function myFunction2() {
46 variable2 = "hello!";
47 // error: variable2 is a constant and can not be redifined
48}
49
50myFunction3(true);
51
52myFunction3(codition) {
53 if(condition) {
54 let variable3 = "helo!" // declared using const
55 }
56 variable3 = "hello!";
57 // error: variable3 is out of scope
58}
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