Who Else Wants to Clear confusion about Javascript Hoisting [Step-by-Step]

JavaScript Hoisting can be confusing sometimes, You may have come across its popular W3 definition.

Hoisting is JavaScript’s default behavior of moving all variable and function declarations at the top of your code.

But, that’s not the right way to define it, to understand what is hoisting

First, you have to know what is Execution Context and How it works:-

Execution Context is a wrapper to help manage the code That is running,

There are lots of lexically sitting code, But which one is currently actually running? Is managed via what’s called execution contexts.

what is hoisting

Hoisting is all about How Execution Context Works,

Execution Context works in two steps, Creation and Execution.

Step 1: Creation phase- JavaScript Engine (Browser) puts function and variable declarations into its memory before it executes any line of code.

Step 2 : Execution phase- Javascript Engine (Browser) executes your code line by line and memory allows Javascript Engine to execute your code before its even declared.

1 Let’s look at Example #1 below to understand it clearly.

uber(); // Uber is executed right here at this line because function uber is already sitting in memory.function uber() {
console.log('call uber') }// Expected Output "call uber"

In JavaScript, variables can be both declared and initialized, This concept becomes important in the context of my next example:

Let’s look at Example #2 below:-

console.log(a);var a = "i'm undefined";
//Here variable a is both Declared and initialized//Expected Output = Undefined

But why it didn’t Work?

JavaScript only hoists declarations, not initializations. If a variable is both declared and initialized, the value will be undefined.

So, why output didn’t throw error here?

Because JavaScript engine when it sets up the memory space for a, it doesn’t know what its value will be, until it starts executing the code.

That placeholder says oh, I don’t know what my value yet, so i’m putting my value called undefined.

Example #3

If you declare the variable after it is used, but initialize it beforehand it will return the value:

Let’s look at Example #3 below.

postHelpful = 'yes! i will share it now';
var postHelpful;// Expected Output =  'yes! i will share it now'

it’s actually a bad idea to rely on hoisting in any way.

You could run into trouble when you realize that value is actually undefined, and not the value you’re expecting.

Now, If you still didn’t understand JavaScript hoisting after reading this blog post, please ask questions in the comments below.

I will personally answer all questions. or alternatively you can Dm me on Facebook too.

If this post was helpful, help me back by clicking the Share button.