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.
About the author:
“Harshit is a technology enthusiast and has keen interest in programming. He holds a B.Tech. degree in Computer Science from JIIT, Noida and currently works as Senior Software Developer at MakeMyTrip. He is also a state level table tennis player. Apart from this he likes to unwind by watching movies and English sitcoms. He is based out of Delhi and you can reach out to him at https://in.linkedin.com/pub/harshit-jain/2a/129/bb5
If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks.