Skip to content

Instantly share code, notes, and snippets.

@maxogden
Last active April 26, 2023 13:05
Embed
What would you like to do?
JS hoisting by example

JavaScript function hoisting by example

Below are many examples of function hoisting behavior in JavaScript. Ones marked as works successfuly print 'hi!' without errors.

To play around with these examples (recommended) clone them with git and execute them with e.g. node a.js

Notes on hoisting

(I may be using incorrect terms below, please forgive me)

When JS is parsed, a first pass is done over each scope, and function definitions are immediately discovered. An example of a function definition is function foo() {}. When a function is declared like this, with a name, that name becomes available to the entire scope when the code in that scope is executed.

A crude timeline of how JS gets executed:

  1. Parse the scope and detect all function definitions
  2. Execute the code top-to-bottom with all functions found in step 1 available as variables

This behavior is called 'hoisting' because it is almost like the function definitions have been 'hoisted' up to the top of the function.

Assignments are not evaluated until the code is executed. An example of an assignment is var foo = function() {} or var foo = function foo() {}. A function must not be associated with an assignment in order for it to be hoisted (see example L)

Wrapping a function in parenthesis (()) is a quick way to convert a function definition into a function expression, which means it does not get hoisted (similar to assigning the function to a variable). I personally do not use this pattern regularly as I find it overly confusing to newbies etc, but I have included it because it is widely used in e.g. jQuery plugins.

I use hoisting as a code organization tool, for example here I rely on hoisting to make parseStream() available on line 20, even though it is defined on line 41, which I think makes that file more readable as I can put the 'meat' of the function at the top.

// A (works)
function sayHi() {
console.log('hi!')
}
sayHi()
// B (works)
sayHi()
function sayHi() {
console.log('hi!')
}
// C (works)
var sayHi = function() {
console.log('hi!')
}
sayHi()
// D (does not work)
sayHi()
var sayHi = function() {
console.log('hi!')
}
// E (does not work)
(function sayHi() {
console.log('hi!')
})
sayHi()
// F (does not work)
sayHi()
(function sayHi() {
console.log('hi!')
})
// G (works)
(function sayHi() {
console.log('hi!')
})()
// H (works)
(function() {
console.log('hi!')
})()
// I (works)
var sayHi = (function() {
console.log('hi!')
})()
// J (works)
var sayHi = (function() {
console.log('hi!')
})
sayHi()
// K (does not work)
sayHi()
var sayHi = (function() {
console.log('hi!')
})
// L (does not work)
sayHi()
var x = function sayHi() {
console.log('hi!')
}
// M
var x = (function sayHi() {
console.log('hi!')
})
x() // works
sayHi() // does not work
@alexnlfm
Copy link

Very useful tutorial! Thanks a lot!

@zimejin
Copy link

zimejin commented May 22, 2017

JavaScript is so wild.

@levarne
Copy link

levarne commented Jul 25, 2017

👍 leka man

@DanChab
Copy link

DanChab commented Aug 6, 2017

awesome...

@HimmelsturmerIX
Copy link

why e.js does not work?

@Ghanshyam-K-Dobariya
Copy link

superb.... great things explained in easiest way...

@tienthanhjlw
Copy link

Thanks :)

Copy link

ghost commented May 16, 2018

i.js is somewhat misleading, in that sayHi does not get assigned a function like in the rest of cases, but the execution result. It would be clearer if the variable had some name other than sayHi in that case (e.g. x, as in l.js and m.js).

@mohamedhafezqo
Copy link

👍

@Clburguete
Copy link

Great. Thanks!

@RajkamalSR
Copy link

Great examples. Thanks ;)

@BDGrace
Copy link

BDGrace commented Jun 5, 2019

Is this outdated now? Looks like at least most of the not working examples work in the console....

@maxogden
Copy link
Author

maxogden commented Jun 5, 2019

@BDGrace you have to clone this repo and run the examples with node <x>.js since the devtools console works differently in regards to hoisting logic

@Josfrax
Copy link

Josfrax commented Jul 1, 2019

Great! Thanks for sharing.

@manasdwd07
Copy link

Great explanation ! Thanks alot :)

@IvanDerlich
Copy link

Excelent explanaition!

@iravinandan
Copy link

iravinandan commented May 9, 2020

cool.
Function declarations are hoisted but not function expressions.

@heytulsiprasad
Copy link

Great examples!

@colpachi
Copy link

Thx for sharing !

@bantya
Copy link

bantya commented Mar 5, 2021

AMZNG!.

@LeonardoLGDS
Copy link

Thanks for the content!

@ggchicote
Copy link

Thanks for sharing!

@citizen46
Copy link

#Suggestion.

You can make a link to it, "see example L" as.

see example L

URL: https://gist.github.com/maxogden/4bed247d9852de93c94c#file-l-js

@dengshenkk
Copy link

Thanks for sharing! 🙏🏻

@mrniamster
Copy link

Thanks for sharing

@benjaminyakobi
Copy link

benjaminyakobi commented Sep 2, 2022

Thanks for sharing!
For those who want to explore more about this topic & more, great article to read:
https://www.freecodecamp.org/news/execution-context-how-javascript-works-behind-the-scenes/

@chickenzombie
Copy link

Thank you very much for this theory unit, it was very helpful :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment