Hoisting (JavaScript)

Hoisting is JavaScript's behavior of moving function and variable declarations to the top of their scope before the code runs. It lets you call a function declared further down in the file.

JavaScript

Function declarations are fully hoisted, so you can call them before they appear in the code. var variables are hoisted too, but only the declaration — their value stays undefined until the assignment line runs.

let and const are hoisted but not initialized, so using them before their declaration throws a ReferenceError (the "temporal dead zone").

Examples

JavaScript

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

Output:

Hi!

JavaScript

console.log(x);
var x = 5;

Output:

undefined

Learn it in a lesson

See also

Back to the Dictionary