🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript Hoisting

Hoisting moves declarations to the top of their scope before the code runs. A var reads as undefined before its line, and a function declaration runs before its line.

var reads as undefined

The declaration moves up, but the value stays on its line. The first read finds no value yet, so it prints undefined.

console.log(score);
var score = 10;
console.log(score);

A function declaration runs early

The whole function moves up with its body. The call works even though it sits above the definition.

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

Hoisting inside a function

Hoisting works inside a function too. The var inside show reads as undefined until its line runs.

function show() {
  console.log(value);
  var value = 5;
  console.log(value);
}
show();

A function expression does not run early

A function stored in a const is not hoisted with its body. The early call throws, and the catch logs the error name.

try {
  sayBye();
} catch (err) {
  console.log(err.name);
}
const sayBye = function () { console.log("Bye"); };
sayBye();

Example

console.log(count);
var count = 3;
console.log(count);
greet();
function greet() { console.log("Hello from above"); }

Key points

  • Hoisting: the move of declarations to the top of their scope before the code runs
  • A var declaration is hoisted, but its value is not.
  • Reading a var before its line gives undefined.
  • A function declaration is hoisted with its body, so it runs before its line.
  • let and const are not hoisted in the same way, so reading them early fails.

In this example, the first line reads count before its var line, so it prints undefined. The second line reads count after the assignment, so it prints 3. The last line calls greet before its definition, and the function still runs.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does console.log(x) print before the line var x = 5?