Question Bank
JavaScript Function Declaration vs Expression Hoisting: Two Explanations Quiz
Difficulty: Medium
Trace mixed declaration / expression calls before either is defined: declaration fully hoisted vs expression-as-var only binding hoisted, plus TDZ for let/const and named function expressions.
JavaScript Function Declaration vs Expression Hoisting: Two Explanations Quiz
Trace mixed declaration / expression calls before either is defined: declaration fully hoisted vs expression-as-var only binding hoisted, plus TDZ for let/const and named function expressions.
435 views
7
Explain the exact output of the snippet below and WHY the first line works while the second throws. Use the term "function declaration hoisting" in your answer.
Examples
Example 1:
Input:
console.log(getNum2(5));
console.log(getNum1(3));
var getNum1 = function (n) { return n + 1; };
function getNum2 (n) { return n + 1; }
Output:
6
TypeError: getNum1 is not a function
Explanation: getNum2 is fully hoisted (both name and body); getNum1 is hoisted as a `var` binding initialised to undefined, so calling it throws.Show the two syntactic shapes side by side and label each: ONE is a function DECLARATION (statement), the other is a function EXPRESSION (value). Note which one is fully hoisted.
Examples
Example 1:
Input: (the side-by-side snippet)
Output: both invocations return 2
Explanation: shape A is the declaration; shape B is the expression.Trace the output of the snippet below where the function expression uses let instead of var. Show the precise error message and explain the difference from the var case in terms of the TEMPORAL DEAD ZONE (TDZ).
Examples
Example 1:
Input:
console.log(getNum(3));
let getNum = function (n) { return n + 1; };
Output: ReferenceError: Cannot access 'getNum' before initialization
Explanation: `let` bindings live in TDZ from the start of the block until their declaration line.Explain why a NAMED function expression like const fn = function inner(n) { return n; } exposes inner only inside its own body, not in the surrounding scope. Demonstrate with a working call from inside the function and a failing reference from outside.
Examples
Example 1:
Input:
const fn = function inner(n) { return n <= 1 ? 1 : n * inner(n - 1); };
fn(4);
Output: 24
Explanation: `inner` is reachable inside its own body for recursion. From outside, `inner` is not defined.