Why Variables are Hoisted as Undefined and Function Declarations Hoisted with Their Values in JavaScript?

Take a look at the piece of code below:

foo(); // Output - Hi

function foo() {
  console.log("Hi");
}
console.log(foo); // undefined

var foo = "hi";

Why does the function foo() output "Hi" while the variable foo is undefined when we log it?

This happens because variables do not hoist their initializations or values, whereas function declarations do.

This behavior is acceptable for functions because function declarations are tied explicitly to the functions they represent. However, variables can assume any value based on an expression that might vary depending on the values used in that expression.

For instance:

var randomGreeting = Math.random() < 0.5 ? "hi" : "hello";
var foo = randomGreeting;

Before randomGreeting is defined with its random expression, it is impossible to determine the value of foo. Therefore, foo's value cannot be known at the point of hoisting, and it defaults to being hoisted as undefined.

Unlike variables, you cannot perform a similar operation with a function declaration, as its value is inherently tied to the declared function. This ensures that the function value is safely hoisted along with its corresponding variable (function name).

Attempting to replicate a similar process with a function turns it into an expression, where the function definition is no longer hoisted.

// Function Expression (Not Hoisted)
try {
  sayHi(); // This will result in an error
} catch (error) {
  console.error(error.message); // sayHi is not a function
}

var sayHi = function () {
  console.log("Hi!");
};

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda