If you can explain why the following outputs between the variables declared with var
and let
/const
, then you can skip this article. Thank you for giving it a look.
console.log(a); //Output: undefined
var a = 1;
console.log(a); //Output: 1
console.log(b); //Output: Reference Error: b is not defined
const b = 2;
console.log(b); //Output: 2
Temporal Scoping
The reason is temporal-scoping. It was introduced in ES6 with the introduction of let
/const
.
A variable declared with let
/const
is unavailable before the declaration. Whereas, if declared with var
, a variable is available in the entire scoping context. However, a value is assigned to it only when the variable is initialized. That is why, in the above example, a
is available to use before its declaration, but it's still undefined
.
Conclusion
ES6 (ECMAScript 6 now) has been around for many years now. The concepts introduced with it are well-supported in all major browsers. However, this aspect of scoping is not talked about much. I hope that you learned something interesting from this post. Until the next one. Cheers!
Top comments (0)