DEV Community

Heru Hartanto
Heru Hartanto

Posted on

What is hoisting javascript ?

Short answer: Hoisting is javascript behaviour that move declaration to the top

yourName="Jiwoo";
console.log(yourName);
var yourName;
Enter fullscreen mode Exit fullscreen mode

What really happen here is during compile phase, javascript will put the variables declaration into memory, visually similar like this:

var yourName;
yourName="Jiwoo";
console.log(yourName);
Enter fullscreen mode Exit fullscreen mode

Okay then let's try another example

number1 = 3;
console.log('number 1', number1);
console.log('number 2', number2);
console.log('number 3', number3);
var number2 = 3;


// output
// number 1 3
// number 2 undefined
// Uncaught ReferenceError: number3 is not defined

Enter fullscreen mode Exit fullscreen mode

What the heck is going on here?, okay let's break it down

Since there is no declaration and initialisation for variable3 it's make sense when the result Uncaught ReferenceError: number3 is not defined

We didn't make any variable declaration for number1, but why it's give correct answer?, it's because javascript "magically" create a declaration for number1 variable and move it to the top. In simple term javascript saying "Hey you're initialize number1 with value 3 but you're not making any declaration, okay lazybones I will do it for you huufh 😩"

number2 are the most confusing, you already initialize and declare your variable but why it's give you undefined?, Remember that hoisting only move declaration?, it's mean that javascript only move number2 declaration to the top and because initialization happen after console.log it will give you undefined as result

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay