Cover image courtesy – here.
This series of posts is aimed at preparing oneself to face JavaScript technical interviews. Here is the source code.
In this post, I shall talk about let vs var, scoping, and hoisting of JavaScript variables.
let vs var
The main difference between let vs var is that they have block vs 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.
Simple example:

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
All undeclared variables in JavaScript are global variables.

ReferenceError vs undefined

Variable 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?!
Hoisting
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
Variable hoist is hoisted in the above code snippet and therefore logs undefined. In case of hoisting, this is how the JavaScript interpreter sees the code:

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!
let vs var in loops
A var in the head of a for loop creates a single storage space for that variable.
In a 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.






Leave a comment