- Home
- Interview Questions
- JavaScript
- Why can you call a function declaration before it is defined…
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: During the creation phase, JavaScript hoists a function declaration completely, both its name and its body, so it can be called from anywhere in its scope. A function expression is only a value assigned to a variable, so it follows the hoisting rules of var, let or const and is not callable until the assignment line runs.
Detailed explanation
Before any code in a scope runs, the engine sets up the scope's bindings. Different kinds of declarations are prepared in different ways:
- Function declaration (
function add() {}): the name is created and immediately bound to the full function object. Calling it above its line therefore works. varholding a function expression (var sub = function () {}): only the variablesubis hoisted, and it starts asundefined. The function is created and assigned only when execution reaches that line. Calling it earlier means callingundefined, which throws a TypeError: sub is not a function.let/constholding a function or arrow: the binding exists but is uninitialised until its line runs. Any access before that throws a ReferenceError.
Arrow functions are always expressions, so they are never hoisted with their body. The same applies to class declarations. They behave like let, so using a class before its declaration throws a ReferenceError.
Name collisions: when a var and a function declaration share a name in the same scope, the function declaration wins during setup, because a var without a value does not overwrite the existing binding. At runtime, any assignment to that var replaces the function. If you use let or const with the same name as a function in the same scope, you get a SyntaxError instead.
Named function expressions: in const f = function inner() {}, the name inner exists only inside the function body. This is useful for recursion and gives clearer stack traces, but inner is not available in the outer scope.
Blocks: in strict mode and ES modules, a function declared inside an if or other block is scoped to that block. In sloppy (non-strict) script code, legacy web-compatibility rules can make it partly visible outside the block. Avoid depending on that behaviour.
Example
console.log(add(2, 3)); // 5 - declaration fully hoisted
function add(a, b) { return a + b; }
console.log(typeof sub); // "undefined"
// sub(5, 1); // TypeError: sub is not a function
var sub = function (a, b) { return a - b; };
// mul(2, 3); // ReferenceError: Cannot access 'mul' before initialization
const mul = (a, b) => a * b;
// Name collision
console.log(typeof greet); // "function" - function wins at setup
var greet = "hi";
function greet() {}
console.log(typeof greet); // "string" - assignment ran
// Named function expression
const fact = function inner(n) {
return n <= 1 ? 1 : n * inner(n - 1);
};
console.log(fact(4)); // 24
// inner(3); // ReferenceError: inner is not definedPractical use: many codebases put helper function declarations at the bottom of a file so the main logic reads first. Teams that want stricter ordering use const with arrow functions, so a call before definition fails loudly instead of quietly working.
Common mistakes
- Saying a
varfunction expression throws a ReferenceError when called early. The variable exists with the valueundefined, so the error is a TypeError. - Assuming arrow functions or classes are hoisted like function declarations. Arrows follow their variable's rules, and classes have a temporal dead zone.
- Forgetting that a later
varassignment with the same name replaces a hoisted function, which causes "is not a function" bugs further down the file. - Expecting the name of a named function expression to be callable from the outer scope.
Follow-up questions
- What does
typeofreturn for avarfunction expression before its line, and why? - How do function declarations inside blocks behave differently in strict and sloppy mode?
- Why might a team's lint rules ban using functions before they are defined?
Interview tip: Name the exact error for each case: a working call for a declaration, a TypeError for a var expression and a ReferenceError for a let/const expression. Interviewers listen for that precision.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More medium JavaScript questions
Related Questions
- How do positional-only (/) and keyword-only (*) parameters work in Python function signatures? · Python · 1 ans
- Why does using a mutable default argument like a list cause bugs in Python? · Python · 1 ans
- What are tagged template literals in JavaScript and when would you actually use one? · JavaScript · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · JavaScript · 1 ans
- Why does a for loop with var and setTimeout print the same value every time? · JavaScript · 1 ans
- Why do lambdas created inside a loop all return the last loop value in Python? · Python · 1 ans
- How do HttpOnly, Secure and SameSite cookie flags protect against XSS and CSRF? · JavaScript · 1 ans
- What is the difference between localStorage, sessionStorage and cookies in the browser? · JavaScript · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)