But before we get into details of ES2015 stuff, let’s discuss what we exactly mean by phrases “function level scope” and “block level scope”.
Block Level Scope: Simple example using C++
For example, in C++, we have declared a variable ‘message’ inside if-condition. When we print the string message inside if condition itself, it works without any problem.
Function level Scope:
In the code snippet above, we have declared and defined a variable message inside the if-condition. Then we print that value using console.log(). We get the output as expected.
- Let: Variables declared using ‘let’ keyword are similar to variables declared using ‘var’ keyword with just once difference. Variables declared using ‘let’ will have block scope and will not get hoisted to the starting of the function. So if we try to access those variables outside their block scope, we’ll get a reference error saying variable is not defined.
Also variables declared with “let” keyword can be redefined but not redeclared.
- Const: Variables declared using “Const” keyword are similar to variables declared using “let” keyword with an additional feature that once declared and defined, their value cannot be changed. Primary use of Const variables is to make read only constants like
Also, it is compulsory to define const variables at the time of declaration itself.