whatstheoutput_

#71: Calling a function before it is defined

Topic: hoisting · Difficulty: ★

console.log(greet());
function greet() { return 'hi'; }

Output

hi

Why

A function DECLARATION (the `function name() {}` form, as a statement, not assigned to a variable) is hoisted completely — both its name and its full body — to the top of the enclosing scope before any code runs. That's different from a var or a function EXPRESSION, where only the variable name is hoisted and the value arrives later. Because greet is already a fully usable function by the time execution reaches the first line, calling it before its textual definition works fine and returns 'hi'.

More hoisting puzzles

Play today's puzzle →