1var:
2 - hoisted (always declared at top of scope, global if none)
3 - function scope
4let:
5 - block scope
6 - not redeclarable
7const:
8 - block scope
9 - not reassignable
10 - not redeclarable
11
12Note: Although it may seem like these hold only semantic meaning, using the
13appropriate keywords helps the JS engines' compiler to decide on what to optimize.
1// ⚡ Initialization
2var a; //✅
3let b; //✅
4const c; //❌ const must have an initial value
5
6// ⚡ Re-Assignment
7var d = 1;
8d = 10; //✅
9
10let e = 2;
11e = 20; //✅
12
13const f = 3;
14f = 30 //❌ const value is always constant and cannot be reassigned
15
16// ⚡ Re-Declaration
17var g = 1;
18var g = 10; //✅
19
20let h = 2;
21let h = 20; //❌ must use variable name only to reassign, cannot be reassigned
22
23const i = 3;
24const i = 30 //❌ cannot be reassigned
25
26// ⚡ Scope [Global, Function or local and block scope]
27// Global Scope ==> Any variable that is declared outside any of the function
28// Function Scope(var) ==> Can be accessed inside the function it was declared and its child
29// Block Scope(let and const) ==> Con be accessed inside curly brackets where it was declared and its child
30
31function myFunction(){
32 var myName1 = 'Asmita';
33 let myName2 = 'Dikshit';
34 const myName3 = 'Sizen';
35 console.log(myName1);
36 console.log(myName2);
37 console.log(myName3);
38
39 if(true){
40 console.log(myName1);
41 console.log(myName2);
42 console.log(myName3);
43
44 var myAge1 = 13;
45 let myAge2 = 15;
46 const myAge3 = 14;
47 console.log(myAge1);
48 console.log(myAge2);
49 console.log(myAge3);
50 }
51
52 console.log(myName1);
53 console.log(myName2);
54 console.log(myName3);
55
56 console.log(myAge1);
57 console.log(myAge2);
58 console.log(myAge3);
59};
60myFunction();
1let num1:number = 1;
2
3function letDeclaration() {
4 let num2:number = 2;
5
6 if (num2 > num1) {
7 let num3: number = 3;
8 num3++;
9 }
10
11 while(num1 < num2) {
12 let num4: number = 4;
13 num1++;
14 }
15
16 console.log(num1); //OK
17 console.log(num2); //OK
18 console.log(num3); //Compiler Error: Cannot find name 'num3'
19 console.log(num4); //Compiler Error: Cannot find name 'num4'
20}
21
22letDeclaration();
23