Our Javascript Code :-
1. Two kinds of “declarations” in JS
var
declarations (function expression)- Are hoisted: the name is registered at the top of its scope, with an initial value of
undefined
. - The assignment (
= function…
) stays in place. Function declarations (e.g.
function foo(){…}
)- Are hoisted with their entire body, so you can call them before they appear in code.
Here, data
is created via a function expression assigned to a var
—so only the name is hoisted, not the function itself.
2. The engine’s two phases
2.1. Creation (or “parsing”) phase
- JS scans your code, finds
var data;
and does:
- It does not yet look at the
= function…
part.
2.2. Execution phase
The code runs top‑to‑bottom:
- Encounter
console.log(data());
- Evaluate
data
→ it’s currentlyundefined
. - Attempt to call it as a function:
undefined()
. Error
Since
undefined
isn’t callable, JS throws:
- Execution stops right there; the assignment below (
data = function…
) is never reached.
3. Why it isn’t "1"
- Order matters: you tried to call
data
before you actually assigned the function to it. - If
data
were a function declaration, it would be available immediately. But here it’s a function expression in avar
assignment.
4. How to fix it
A. Use a function declaration
Function declarations are hoisted with their body, so data()
works immediately.
B. Move the call below the assignment
5. Key Points :-
var
names are hoisted without their initializers (so they start asundefined
).- Function expressions (e.g.
var f = function(){…}
) do not get hoisted as callable functions. - Attempting to call an
undefined
value throws a TypeError. - Always be mindful of hoisting and whether you’re using a function declaration or expression.
✔ Final Answer:
C) TypeError
This question appeared in the Infosys interview, testing the candidate’s knowledge of hoisting and difference between function expression and function declaration in JavaScript.