What is Hoisting in JavaScript?

TechLoons
2 min readMay 31, 2023
Photo by Juanjo Jaramillo on Unsplash

In JavaScript, hoisting is the process of moving all variable and function declarations to the top of their respective scopes. This means that even though a variable or function may be declared in the middle of a script, it can be used anywhere in the script after its declaration.

For example, the following code will print “Hello, world!” even though the greet() function is declared in the middle of the script:

console.log("Hello, world!");

function greet() {
console.log("Hello, world!");
}

greet();

This is because the greet() function is hoisted to the top of the script before it is executed.

Hoisting can be a useful feature, but it can also lead to errors if it is not used correctly. For example, the following code will throw an error because the foo variable is not declared before it is used:

console.log(foo);

var foo = "bar";

To avoid errors, it is always best to declare variables and functions at the top of their respective scopes.

In addition to variables and functions, hoisting also applies to class declarations. For example, the following code will create a new Person object even though the Person class is declared in the middle of the script:

var person = new Person();

class Person {
constructor() {
this.name = "John Doe";
}
}

This is because the Person class is hoisted to the top of the script before it is executed.

Hoisting is a fundamental concept in JavaScript that is important to understand in order to write correct and reliable code.

In other words, we can also say that :

Hoisting in JavaScript is a behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that variables and functions can be accessed and used before they are declared in the code. However, only the declarations are hoisted, not the initializations or assignments. It’s important to declare variables and functions at the top of their scope to avoid confusion and maintain code readability.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

TechLoons
TechLoons

Written by TechLoons

Welcome to TechLoons, your go-to source for the latest tips and information on a wide range of topics.

No responses yet

Write a response