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//let is used to declare the variable or initialize a variable..
2//let variable can be updated in future.
3//Its block scope and we cannot redeclare it.
4
5let a; // Initializing the variable.
6let b = 4; // Initializing and declaring variable.
7let b = 5; //Error:- cannot redeclare a value but we can update the value.
8
9//var is just like let but var is used to declare a variable value at top of
10//the program, its hoisted.
11
12var a; // Initializing the variable.
13var b = 4; // Initializing and declaring variable.
14var b = 5; //b will be redeclared and we can update its value.
15
16//const variable should be declared and intialized at same time.
17//const variable cannot be updated in future.
18//we cannot even redeclare the variable in future.
19
20const a = 10; //Initilizing and declaring a variable at a time.
21const b; //Error:- const should be declared and intialized.
22const a = 11 // Error:- cannot redeclare the variable again.
1The difference is that with const you can only only assign a value to a variable
2once, but with let it allows you to reassign after it has been assigned.
1var:
2 * hoisted(global scope)
3 * function scope
4let:
5 * block scope
6 * reassignable
7 * not redeclarable
8const:
9 * block scope
10 * not reassignable
11 * not redeclarable
1// var is a function scope ***
2if(true){
3 var varVariable = 'This is var';
4 var varVariable = 'This is var again';
5}
6
7console.log(varVariable); // This is var again
8
9// let is a block scope ***
10if(true){
11 let letVariable = 'This is let';
12 let letVariable = 'This is let again';
13
14 // let variable can't re-define but we can re-assign value
15
16
17 console.log(letVariable); // let letVariable = 'This is let again';^SyntaxError: Identifier 'letVariable' has already been declared
18}
19
20console.log(letVariable); //ReferenceError: letVariable is not defined
21
22
23
24// const variable can't re-define and re-assign value
25// const is a block scope ***
26if(true){
27 const constVarible = {
28 name: 'JavaScript',
29 age: '25 years',
30 };
31 constVarible.name = 'JS';
32
33 console.log(constVarible) // {name: 'JS',age: '25 years'} <= we can update const variable declared object
34}