links: JS MOC


JS before executing your code parses it, and adds to its own memory every function and variable declaration it finds and holds them in memory. This is called hoisting

Technical definition

Hoisting is when JS interpreter moves all variables and function declarations to the top of the current scope. Hoisting is done during the interpreter’s first run through the code.

Examples

Suppose we have a function:

function sendMonkeyToMars() {
	console.log('sending monkey to mars')
}

Due to hoisting we can technically invoke sendMonkeyToMars() before it is declared.

sendMonkeyToMars()
function sendMonkeyToMars() {
	console.log('sending monkey to mars')
}

With functions, this only happens for function declarations. Like in the case above

Not with function expressions

sendMonkeyToMars()
var sendMonkeyToMars = function() {
	console.log('sending monkey to mars')
}

In this case the var definition is hoisted and initialized with undefined as value, something like this

var sendMonkeyToMars = undefined
sendMonkeyToMars()
sendMonkeyToMars = function () {
	console.log('sending monkey to mars')
}

Running this code will give you TypeError: bark is not a function error.

const and let declarations are hoisted, too, but they are not initialized to undefined like var

let sendMonkeyToMars = function () {
	console.log('sending monkey to mars')
}

In this case if you invoke sendMokeyToMars() before declaring it, it will give you a Reference Error: cannot access 'sendMonkeyToMars' before initialization error.


tags: fundamentals , javascript