How does hoisting work in JavaScript?

sanju saini
Jan 8, 2021

--

Hoisting is a JavaScript mechanism where variable and function declarations are put into memory during the compile phase. This means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.

However, the value is not hoisted with the declaration.

The following snippet:

console.log(hoist)
var hoist = "value"

is equivalent to:

var hoist
console.log(hoist)
hoist = "value"

Therefore logging hoist outputs undefined to the console, not "value".

Hoisting also allows you to invoke a function declaration before it appears to be declared in a program.

myFunction() // No error; logs "hello"
function myFunction() {
console.log("hello")
}

But be wary of function expressions that are assigned to a variable:

myFunction() // Error: `myFunction` is not a function
var myFunction = function() {
console.log("hello")
}

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

--

--

sanju saini
sanju saini

Written by sanju saini

Senior Software Engineer with 4.5+ years of experience in full-stack development, specializing in Python, Golang, PHP, Django, FastAPI, React, and RESTful APIs.

No responses yet

Write a response