Function Expression vs Declaration: A Deep Dive into JavaScript Hoisting, Explained The Unexpected Behavior of Function Expressions with var keyword

Our Javascript Code :-

console.log(data());
var data = function () { return "1"; };

1. Two kinds of “declarations” in JS

  1. 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.
  2. 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:

        var data = undefined;

  • It does not yet look at the = function… part.

2.2. Execution phase

The code runs top‑to‑bottom:

  1. Encounter console.log(data());
    • Evaluate data → it’s currently undefined.
    • Attempt to call it as a function: undefined().
  2. Error

    • Since undefined isn’t callable, JS throws:

                        TypeError: data is not a function
    • 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 a var assignment.


4. How to fix it

A. Use a function declaration

console.log(data()); // → "1"
function data() { return "1"; }

Function declarations are hoisted with their body, so data() works immediately.

B. Move the call below the assignment

var data = function() {
return "1"; }; console.log(data()); // → "1"

5. Key Points :-

  • var names are hoisted without their initializers (so they start as undefined).
  • 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.

Post a Comment

Previous Post Next Post