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.
1//functional scope
2 var a; // declaration
3 a=10; // initialization;
4//global scope
5// re-initialization possible
6 let a;//only blocked scope & re-initialization possible
7 a=10;
8let a =20;
9if(true){
10 let b =30;
11}
12console.log(b); // b is not defined
13const // const also blocked scope,Re-initialization and re-declaration not possible
14const a; // throws error {when we declaring the value we should assign the value.
15const a =20;
16if(true){
17 const b =30;
18}
19console.log(b); // b is not defined
20console.log(a); // no output here because code execution break at leve b.
21
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}