Cover image courtesy – here.
In this post, I shall talk about
The main difference between
var is that they have
function scope respectively.
What is scope?
Scope is a set of rules for looking up variables by their identifier name.
In simpler words, scope determines visibility for variables.
In the first case, there is a ReferenceError, because the variable
tmp is declared outside the scope of the executing code.
Declaration vs Definition of a variable
var tmp Here, the variable
tmp is only declared. It isn’t defined, i.e. it isn’t assigned any value.
var tmp = 123 The variable
tmp is both declared and defined here.
Variable defined, but not declared
ReferenceError vs undefined
hoist is undeclared, but notice the text for
ReferenceError in the above message –
hoist is not defined! Think of opening a PR to one of the browser JS engines to fix this message?!
hoist is hoisted in the above code snippet and therefore logs
Temporal Dead Zone
A variable declared by
let has a temporal dead zone (TDZ). When entering its scope, it cannot be accessed until the execution reaches its declaration.
In simpler words,
letvariables aren’t hoisted!
var in loops
var in the head of a
for loop creates a single storage space for that variable.
let, a new storage space is created for each iteration of the loop.
The next time, someone asks you SCOPE, these are the things to keep in mind!
Source code for all the above code snippets is here.