What happens when you log a var before declaration? Hoisting in Javascript? Asked in an Epam interview


Our Javascript Code:

console.log(x);
var x = "Hello"; console.log(x);

Step-by-Step Explanation

🔸 Step 1: Hoisting in JavaScript

In JavaScript, variable declarations (var, function) are hoisted to the top of their scope during the compilation phase.

So the code:

console.log(x);
var x = "Hello"; console.log(x);

Is interpreted by JavaScript like this behind the scenes:

var x; // Declaration is hoisted to the top
console.log(x); // At this point, x exists but is `undefined` x = "Hello"; // Now x is assigned the value "Hello" console.log(x); // So it logs "Hello"

✔ Final Answer:

A) undefined Hello

This question appeared in the Epam 2nd round of interview, testing the candidate’s knowledge of hoisting with var variable in JavaScript.


🚨 Common Mistake:

People often assume the first console.log(x) should throw a ReferenceError but it doesn't!

That would only happen if you used let or const:

console.log(x);
let x = "Hello"; // ❌ ReferenceError: Cannot access 'x' before initialization

Remember Key Points:

  • "var" declarations are hoisted, and initialize with undefined during memory creation phase of Execution Context. but let and const are not initialize with undefined.
  • So before the assignment, the variable "var" exists with the value undefined. but the variable "let" and "const" give ReferenceError due to access before initialize any value.

Post a Comment

Previous Post Next Post