JS Shorts — Hoisting

Prakhar Jaiswal
2 min readOct 17, 2020

--

Hoisting, in layman terms is a way of moving the variable (declared using var keyword) and function declarations to the top of the code block.

What actually happens is, during the compile phase of the code these variable and function declarations are put in memory. One important thing to note here is that only the declarations are processed during this phase, the variable assignments stay where they were originally written.

  • Let’s understand this better with the below examples,
console.log(foo);
var foo;
foo = 4;
console.log(foo);

This code produces the below output,

undefined
4

Notice how the value was assigned only after it moved past it’s actual initialisation in code.

  • Let’s see how this pans out with functions,
console.log(foo);foo();function foo() {
console.log('foo');
}

This produces the below output,

ƒ foo() {
console.log(‘foo’);
}
foo

Notice how foo() is accessible even before it’s defined.

  • Let’s cover one last use case with let and const. The lexically declared variables (with let or const) are also hoisted, but they remain uninitialised until the statement in code is evaluated.
console.log(a); // undefined
console.log(b); // Uncaught ReferenceError: b is not defined
var a;
let b = 'b';

This means that the variable remains in a temporal dead zone between the start of code block and initialisation. Accessing the variable during this point will cause a ReferenceError. This error is caused due to the fact that the declaration is moved to the top because of hoisting, so the compiler knows that this lexical variable has an actual value to be initialised at a later point of time, hence it throws an error instead of showing a wrong value like undefined.

Image by Mudassar Iqbal from Pixabay

—That’s all for today

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

--

--

No responses yet

Write a response