DEV Community

Sajin Joe J
Sajin Joe J

Posted on

Hoisting in javascript

Hoisting is the default behaviour of javascript where all the variable and function declarations are moved on top.

1. Function Hoisting

greet();

function greet() {
    console.log("Hello Sajin");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Hello Sajin
Enter fullscreen mode Exit fullscreen mode

This works because function declarations are hoisted.

2. var Hoisting

console.log(name);

var name = "Sajin";
Enter fullscreen mode Exit fullscreen mode

Output:

undefined
Enter fullscreen mode Exit fullscreen mode

JavaScript behaves roughly like:

var name;

console.log(name);

name = "Sajin";
Enter fullscreen mode Exit fullscreen mode

The declaration is hoisted, but the value assignment is not.

3. let and const

let and const are also hoisted internally, but they cannot be accessed before their declaration.

console.log(name);

let name = "Sajin";
Enter fullscreen mode Exit fullscreen mode

This gives:

ReferenceError
Enter fullscreen mode Exit fullscreen mode

The same applies to const:

console.log(age);

const age = 25;
Enter fullscreen mode Exit fullscreen mode

4. Why is Hoisting useful?
The most practical example is function declarations:

calculate();

function calculate() {
    let a = 10;
    let b = 20;

    console.log(a + b);
}
Enter fullscreen mode Exit fullscreen mode

Output:

30
Enter fullscreen mode Exit fullscreen mode

It allows you to organize code so that the main logic appears before the detailed function implementations.

Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the creation phase, before code execution.

Top comments (0)