JavaScript Interview Essential — Episode 4: Understanding Hoisting in JavaScript
Have you ever heard a term in JavaScript called "hoisting" and wondered what it's all about? Let's break it down with a simple analogy and some easy-to-understand examples.
What is Hoisting?
Imagine you're in a classroom, and the teacher calls out your name for attendance before you even enter the room. In JavaScript, hoisting is similar. It's like the teacher (JavaScript engine) knows your name (variable or function) even before you've entered the room (declared it in the code).
A Simple Example
console.log(myPet); // Output: undefined
var myPet = 'Rex';
This could cause an error because myPet
is used before it's declared. But thanks to hoisting, myPet
is known (but not yet defined) at the top, so the output is undefined
.
Real-World Example: Cooking in the Kitchen
Imagine you’re in the kitchen preparing to cook a meal. You have a recipe book (your code) and a list of ingredients (variables and functions).
Var Hoisting
You decide to make a salad, and you need lettuce. You look in your fridge, and even though you haven’t bought the lettuce yet, you know you will have it. This is like var
hoisting:
console.log(lettuce); // Output: undefined
var lettuce = 'Romaine';
In this example, you know about the lettuce (var lettuce
), but you don't know what type it is (undefined
) until you get it (Romaine
).
Let and Const Hoisting
Now, you decide to make a fruit salad and need apples. However, in this case, you can’t even think about apples until you’ve bought them. This is like let
and const
hoisting:
console.log(apples); // ReferenceError: Cannot access 'apples' before initialisation
let apples = 'Granny Smith';
Here, trying to use apples
before buying them (let apples
) results in an error because let
and const
only allow you to acknowledge the ingredient after you have it.
Function Hoisting
Finally, you decide to bake a cake. You have a recipe for the cake, and even though you haven’t started making it yet, you know exactly how it will be made. This is like function declaration hoisting:
bakeCake(); // Output: Baking a chocolate cake!
function bakeCake() {
console.log('Baking a chocolate cake!');
}
In this example, the recipe for the cake (the function bakeCake
) is known and defined before you start making it, just like how function declarations are hoisted to the top in JavaScript.
Hoisting in JavaScript is like preparing to cook a meal. You might know some ingredients or recipes before you start cooking, but you can’t use others until you have them. Understanding how hoisting works helps you write better and more predictable code, just like knowing your ingredients and recipes makes cooking a meal more accessible and enjoyable!
Hoisting with Variables
Different types of variables behave differently with hoisting.
Var
Variables declared with var
are like students known to the teacher even before entering the classroom, but their details still need clarification.
console.log(myFruit); // Output: undefined
var myFruit = 'Apple';
Let and Const
Variables declared with let
and const
are like students who are unknown to the teacher until they enter the classroom. If the teacher calls their name before they enter, it causes an error.
console.log(myDrink); // ReferenceError: Cannot access 'myDrink' before initialisation
let myDrink = 'Lemonade';
Hoisting with Functions
Functions in JavaScript also experience hoisting but in a slightly different way.
Function Declarations
Function declarations are like students, who are known to the teacher and have their details clear even before they enter the classroom.
sayHello(); // Output: Hello!
function sayHello() {
console.log('Hello!');
}
Function Expressions
Function expressions are like students whose details are known to the teacher but not clear until they enter the classroom.
sayGoodbye(); // TypeError: sayGoodbye is not a function
var sayGoodbye = function() {
console.log('Goodbye!');
};
Tips to Avoid Confusion
To keep your code clear and avoid surprises:
- Declare Variables at the Start: It’s like giving the teacher a list of students before the class starts.
- Use Let and Const: They’re like students who aren’t confused by being known before entering the classroom.
- Understand Functions: Know the difference between function declarations (known and clear) and function expressions (known but not clear).
Common Interview Questions
What will be the output of the following code?
console.log(typeof animal);
var animal = 'Tiger';
- A)
'undefined'
- B)
'string'
- C)
'Tiger'
- D)
ReferenceError
Which statement about hoisting is true?
- A) Only variable declarations are hoisted, not initialisations.
- B)
let
andconst
variables are hoisted and initialised withundefined
. - C) Function expressions are hoisted to the top of their scope.
- D) Hoisting does not occur in JavaScript.
What will be the output of the following code?
var greeting = 'Hello';
(function() {
console.log(greeting);
var greeting = 'Hi';
})();
- A)
'Hello'
- B)
'Hi'
- C)
'undefined'
- D)
ReferenceError
What is the output of the following code snippet due to hoisting?
function sayHello() {
console.log(name);
var name = 'Alice';
}
sayHello();
- A)
'Alice'
- B)
'undefined'
- C)
ReferenceError: name is not defined
- D)
''
(an empty string)
Which of the following statements correctly describes the behaviour of the let
keyword about hoisting?
- A) Variables declared with
let
are hoisted to the top of their block scope and initialised withundefined
. - B) Variables declared with
let
are not hoisted and can only be used after their declaration. - C) Variables declared with
let
are hoisted to the top of their function scope. - D) Variables declared with
let
are hoisted to the top of their block scope but are not initialised.
Answers: Common Interview Questions
- Answer: A)
'undefined'
- Answer: A) Only variable declarations are hoisted, not initialisations.
- Answer: C)
'undefined'
- Answer: B)
'undefined'
- Answer: D) Variables declared with
let
are hoisted to the top of their block scope but are not initialised.