Javascript followed function level and global scope for a very long time which created a lot of problems. Developers could declare a variable anywhere as global and variables lived even outside loops and if else blocks because of the function level scope.
Ecmascript 6 came up with support for block level scoping using 2 new keywords to define a variable. var still is supported along with const and let.
const: It is used to define a constant whose value cannot be changed nor it can be re-declared in the block scope where it is defined. Run the following code.
1 2 3 4 5 6 |
const constantVariable1 = 900; { const constantVariable1 = 200; alert(constantVariable1); //alerts 200 } alert(constantVariable1); //alerts 900 |
Add the following line after the last alert statement now:
1 |
constantVariable1 = 500; // Error:Identifier 'constantVariable1' has already been declared |
Note: if you declare an Object constant then its values can be changed using the dot(.) operator.
let: It is used to define a variable whose value can be changed but it cannot be re-declared in the block scope where it is defined. Run the following code.
1 2 3 4 5 6 7 8 |
let constantVariable = 900; alert(constantVariable); // alerts 900 { let constantVariable = 200; alert(constantVariable); // alerts 200 } constantVariable = 500; alert(constantVariable); // alerts 500 |
Browser Support: Ecmascript 6 is supported by all modern browsers. The above mentioned features are compatible from IE 11+ and Edge, Android browser for version 6.0 and above and iOS version 10 and above.