ple and reasonably assume that the author intended to create a new variable
x
whose
scope is the block formed by the
if
statement, which is not what will happen.
If you are thinking “Why does
var
allow you to do these things that are confusing
and useless?”, you now understand why
let
came about. You can certainly use
var
in
a responsible and clear fashion, but it’s painfully easy to write code that is confusing
and unclear. ES6 could not simply “fix”
var
, as that would break existing code; hence,
let
was introduced.
I cannot think of an example that uses
var
that could not be written better or more
clearly using
let
. In other words,
var
offers no advantage over
let
, and many in the
JavaScript community (including myself) believe that
let
will eventually completely
replace
var
(it’s even possible that
var
definitions will eventually become deprecated).
So why understand
var
and hoisting? For two reasons. First, ES6 will not be ubiqui‐
tous for some time, meaning code will have to be transcompiled to ES5, and of course
much existing code is written in ES5. So for some time to come, it will still be impor‐
tant to understand how
var
works. Second, function declarations are also hoisted,
which brings us to our next topic.
Function Hoisting
Like variables declared with
var
, function declarations are hoisted to the top of their
scope, allowing you to call functions before they’re declared:
f
();
// logs "f"
function
f
() {
console
.
log
(
'f'
);
}
Note that function expressions that are assigned to variables are not hoisted; rather,
they are subject to the scoping rules of variables. For example:
f
();
// TypeError: f is not a function
let
f
=
function
() {
console
.
log
(
'f'
);
}
The Temporal Dead Zone
The temporal dead zone (TDZ) is a dramatic expression for the intuitive concept that
variables declared with
let
don’t exist until you declare them. Within a scope, the
TDZ for a variable is the code before the variable is declared.
For the most part, this should cause no confusion or problems, but there is one aspect
of the TDZ that will trip up people who are familiar with JavaScript prior to ES6.
Function Hoisting | 127