Unexplored territory of let declaration
Like most of us I have also been using let
to declare variables in my personal and professional projects and was pretty confident about it. Recently, I came across something that was a total surprise to me. Let me call it the unknown territory(this was the case for me) or rather the least known area about let
declaration.
Before we start exploring, let us write down what we know about let
:
- Variables are declared in block scope and cannot be accessed outside of the block.
- Values assigned can be changed n number of times within the scope.
- Redeclaring the same variable within the function or block scope raises syntax error.
Explore the unexplored
We are familiar with the popular concept of variable hoisting. Variables declared with var
keyword are hoisted to the top of the lexical scope.
What is not well known is hoisting happens in case of let
declaration as well but in a slightly different manner. When you declare a variable with let
, the declaration is hoisted but the variable cannot be accessed until it’s definition is evaluated. In the meantime variable is in TDZ(Temporal Dead Zone).
Unlike with simply undeclared variables and variables that hold a value of undefined
, using the typeof
operator to check for the type of a variable in TDZ will throw a ReferenceError
:
Let us run through one scenario where I tried to assign an invalid value to a variable declared with let
. What happened next was very interesting, I was unable to reassign values as it permanently stuck in temporal dead zone. This was because V8 engine was not able to process invalid value to come out of TDZ.
This behaviour is unique to the let
keyword. If you try my example with var
instead of let
, it works fine. Only let
is not initialised until its definition is evaluated.😅
If you liked reading this, don’t forget to clap. 👏👏
You can also follow me on twitter @Akash940 for JavaScript or React updates.
Thank-you!