let VS var VS const
What are the differences? The main difference is the scoping
In nutshell, block scope is the code that is enclosed in curly braces
In the code above we are defining the variable num two times. Lines 1 and 3. What we will see in the console.log of lines 4 and 7?
Well, in line 4 we will see 10 and in line 7 we will see 50. Why is that?
Although we have the same variable name, the scope is different. The scope of the variable in line 1 is the global while the other's scope is between lines 2 and 5.
The variables that are declared with const have the same behavior like we declare them with let. They are Blocked Scope too.
So, what's the difference then? The difference is that the variables are constant and their value won't change during the application execution.
If we try to change the value of a constant variable, a run-time error will be thrown (const_scope_2.js)
const variables are not immutable
It's a common misconception that since we can not change the value of a variable, then we have an immutability. Well, no! We are not allowed to change the value of a variable by assigning a new object (line 10), but we are allowed to change the value of a property of this object (line 6)
Declaring variables with var is error prone as it is easier the value to be changed on any internal scope
I am an Angular GDE, content creator who loves sharing knowledge