DEV Community

Heru Hartanto
Heru Hartanto

Posted on

2 1

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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay