← All tutorials

GoCareerGo Tutorials

JavaScript Tutorial

Variables to closures, promises, the DOM and OOP — a complete JS reference.

Variable Hoisting

JavaScript moves declarations to the top of their scope during compilation — but initialization stays where it is.

Hoisting means the JS engine registers variable and function declarations before running any code line by line.

  • var declarations are hoisted and initialized to undefined
  • let/const are hoisted but stay uninitialized (temporal dead zone) until their line runs
  • Function declarations are fully hoisted, including their body
  • Function expressions and arrow functions are NOT hoisted the same way
console.log(x); // undefined (not an error)
var x = 5;

console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 5;

greet(); // Works! Function declarations hoist fully
function greet() { console.log('hi'); }
Tip

Say clearly: 'hoisting moves the declaration, not the assignment' — that one sentence answers most follow-ups.