Why aren't function expressions hoisted?

Just wondering, why aren’t function expressions hoisted? Also, could someone please give me an example of a function being hoisted? It still confuses me a bit. Thanks :+1:

As to the why, I’m not sure, but here is an example of a function being hoisted versus an arrow function (treated the same as a function expression) not being hoisted:


console.log(sayHello('galds')); //calling the function before it is defined

function sayHello(name) {
  return `Hello, ${name}!`;
}

//The function was hoisted, so the code works
//Prints: Hello, galds!

console.log(sayHi('galds')); //again, calling the function before it is defined

const sayHi = name => `Hi, ${name}!`;

//the arrow function was not hoisted, so we get an error when the 
//console.log() statement is executed
//Prints: ReferenceError: sayHi is not defined

That makes a lot more sense now. Thanks for clearing it up. Does the function get hoisted to the top of the code though? Like right at the top.

1 Like

There are some in-depth explanations:

https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
https://www.digitalocean.com/community/tutorials/understanding-hoisting-in-javascript

the MDN docs say:

This is because of how context execution works in JavaScript.

Which is not very technical, but generally enough. I am sure there are even more in-depth articles.

2 Likes

Thanks for the help :slight_smile:

1 Like

Not sure that the exact order ie. right at the top, second from the top, etc. really matters. Each function declaration is initialized, and ready to be used. In the following example each function calls the function after it. Changing the order the functions appear in the program makes no difference.

console.log(greet('galds'));

function greet(name) {
  return `${randomGreeting()}, ${name}!`;
}

function randomGreeting() {
  return ['Hello', 'Hi', 'Good morning', 'Nice to see you'][getIndex()];
}

function getIndex() {
  return Math.floor(Math.random() * 4);
}

If we were to change any of the functions to a function expression or an arrow function, we would get an error.

2 Likes