#65: Calling a var-assigned function before its line
Topic: hoisting · Difficulty: ★★
try {
console.log(greet());
} catch (e) {
console.log(e.constructor.name);
}
var greet = function () { return 'hi'; };
console.log(typeof greet);Output
TypeError function
Why
var declarations are hoisted to the top of their scope, but only the declaration — not the assignment. So at the top of the script, greet already exists but holds undefined, not a function. Calling undefined() throws a TypeError ('greet is not a function'), which the try/catch reports by name. Only after the assignment line runs does greet become a real function, so the later typeof check reports 'function'. This is the key difference from a function DECLARATION (function greet(){}), which is hoisted fully initialized and callable before its line.