JavaScript is a fascinating and sometimes perplexing programming language that behaves unexpectedly in certain scenarios. One of these concepts is hoisting, where we may not fully grasp what is happening behind the scenes. In this guide, I will explain hoisting in JavaScript with examples to shed some light on this topic.
What is Hoisting?
To understand hoisting, we need to grasp how the JavaScript engine executes code. When we run JavaScript code, the engine creates a global execution context.
The global execution context consists of two phases: creation and execution.
During the creation phase, JavaScript moves all variable declarations and function declarations to the top. Then, during the execution phase, the engine executes the code line by line from top to bottom. This process of moving declarations to the top is known as hoisting.
Now that we have a theoretical understanding of hoisting, let's explore some code examples.
- Variable Hoisting
Variables declared with the var
keyword are hoisted. If we initialize a variable before declaring it, it will work perfectly fine. For example:
name = "John";
console.log(name);
var name;
// Output: John
Note that only the declaration is hoisted, not the initialization. For example:
console.log(name);
var name = "John";
// Output: undefined
Variables declared with let
and const
are also hoisted, but they are not initialized with undefined
like variables declared with var
. For example:
name = "John";
console.log(name);
let name;
// Output: ReferenceError: Cannot access 'name' before initialization
- Function Hoisting
Function declarations are hoisted, which means a function can be called before it is defined. For example:
console.log(sayHello("John"));
function sayHello(name) {
return `Hello, ${name}!`;
}
// Output: Hello, John!
However, this is not the case for function expressions and arrow functions. Let's see an example:
console.log(sayHello("John"));
const sayHello = function () {
return `Hello, ${name}!`;
}
// Output: ReferenceError: Cannot access 'sayHello' before initialization
Conclusion
Hoisting is an important concept in JavaScript that is often overlooked. Understanding hoisting is crucial, especially for technical interviews. In this article, we have discussed how hoisting works under the hood and provided examples of variable and function hoisting. I hope this clears up any doubts you may have had regarding hoisting.