Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

Why does using a var before its declaration return undefined?

Do you know what will be the output of this code?

JavaScript
console.log(a);
var a = 5;
Show answer and explanation

The answer is undefined.

The declaration var a is hoisted to the top and initialized with undefined. The assignment a = 5 stays where it is, so it hasn’t run yet when console.log executes.

Take the full quiz Next question →

More Scope & Hoisting questions

  1. Is a var loop variable accessible after a for loop?
  2. Why does var in a loop with setTimeout print 3 3 3?
  3. Why does let in a for loop fix the setTimeout closure problem?
  4. What is the temporal dead zone in JavaScript?
  5. Can you call a function before it is declared in JavaScript?

Related topics