What is hoisting in JavaScript?

Supakon_k
2 min readJan 4, 2023

--

Photo by Claudio Schwarz on Unsplash

In JavaScript, hoisting refers to the behavior of variable declarations being moved to the top of their containing scope. This means that a variable can be used before it is declared.

For example:

console.log(x);  // Output: undefined
var x = 5;

Even though the variable x is declared after it is logged into the console, it is still defined and its value is undefined. This is because the declaration of the variable is hoisted to the top of the code block, so it is available to be used throughout the block.

It is important to note that only the declarations of variables are hoisted, not their assignments. In the example above, the assignment x = 5 is not hoisted, so the value of x is undefined until the assignment is executed.

In JavaScript, function declarations are also hoisted, meaning they can be used before they are defined. For example:

foo();  // Output: "hello"

function foo() {
console.log("hello");
}

Here, the function foo is called before it is defined, but it still executes correctly because the declaration of the function is hoisted to the top of the code block.

It is important to note that only function declarations are hoisted, not function expressions. For example:

bar();  // Output: Uncaught TypeError: bar is not a function

var bar = function() {
console.log("hello");
}

Hoisting can lead to confusing or unexpected behavior in JavaScript, so it is generally a good practice to declare variables at the top of their scope to avoid confusion.

--

--

Supakon_k
Supakon_k

Written by Supakon_k

Software Engineer & Freelancer from Thailand.

No responses yet