Search⌘ K
AI Features

Solution Review: Hoisting

Explore how JavaScript hoisting works by examining variable declaration behaviors and output results in sample code. Understand why declarations are lifted while initializations remain in place, helping you grasp this key language concept necessary for interview success.

Question 1: Solution review

Explanation

Run the code from the question below:

Javascript (babel-node)
function Add(){
console.log(answer)
var answer = 2
};
Add()

The above code displays undefined as an answer due to the concept of hoisting in Javascript.

Hoisting

In JavaScript, a variable can be declared after it has been used. This is because variable declarations using var are hoisted to the top of their functional scope at compile time. Hence, a variable can be initialized and used before it has been declared.

Let’s take a look at an example:

Javascript (babel-node)
text = "123"
console.log(text)
var text

Why did we not run into an error and get 123 as an output? It’s because the variable declaration on line 3 gets hoisted to the top. Hence, the above code is interpreted as follows at compile time:

Javascript (babel-node)
var text
text = "123"
console.log(text);

Similarly, the code in our question will be interpreted by JavaScript in the following way:

Javascript (babel-node)
function Add(){
var answer
console.log(answer)
answer = 2
};
Add()

As you can see, due to hoisting, the variable declaration var answer gets lifted to the top of the current scope.

Note: Only the declarations get hoisted to the top, not the initializations.

This is why we see undefined in the output and not 2.

Questions related to hoisting can be asked in a senior or junior level frontend interview, so let’s take a look at another question that can be asked during such interviews.

Question 2: Solution review

Explanation

As discussed above, the code will be interpreted as follows due to hoisting:

Javascript (babel-node)
var temp = "hi"
function display(){
var temp
console.log(temp)
temp = "bye"
}
display()

In the above question, var temp = 'bye' is a function scoped variable. At compile-time, its declaration var temp is hoisted to the top of the display() function. Because the value bye is set after line 4, upon compilation, output displays undefined.


Let’s move on to the next challenge.