whatstheoutput_

#66: Logging a var before its declaration

Topic: hoisting · Difficulty: ★

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

Output

undefined

Why

JavaScript hoists var declarations to the top of their enclosing function (or the top level here), but it only moves the DECLARATION, not the assignment. So the engine effectively sees 'var x; console.log(x); x = 5;'. At the point console.log runs, x has been declared but not yet assigned, so it holds the default value undefined. This is different from let or const, which are also hoisted but stay in a temporal dead zone and throw a ReferenceError if read before their declaration line executes.

More hoisting puzzles

Play today's puzzle →