Top 5 JavaScript Interview Problems (With Real-World Solutions)

1.31K 0 0 0 0

Chapter 2: Variable Scope, Hoisting & Closures β€” with Real Interview Challenges

🧠 Why This Matters

This isn’t just about var, let, and const.

This is about:

  • Why your variables aren’t behaving the way you expect
  • Why callbacks act weird inside loops
  • How to create memory-efficient logic in JavaScript
  • Solving real bugs in live interview environments

Interviewers use scope, hoisting, and closure challenges to separate people who know syntax from those who know how JavaScript really works under the hood.

Let’s break it down β€” and then apply it in battle-tested, real-world problems.


πŸ”Ž Scope in JavaScript

Scope defines where variables and functions are accessible.

πŸ’‘ Types of Scope:

Scope

Description

Global

Declared outside any function

Function

Variables available only inside functions

Block

Declared with let or const inside {}

Lexical

Scope preserved based on code structure


βœ… Scope Example:

function run() {

  let x = 5;

  if (true) {

    let y = 10;

    console.log(x); // βœ… 5

    console.log(y); // βœ… 10

  }

  console.log(y); // ❌ ReferenceError

}


πŸš€ Real-World Challenge #1: Scope Shadowing

var a = 1;

 

function outer() {

  var a = 2;

  function inner() {

    console.log(a);

  }

  return inner;

}

 

const result = outer();

result(); // What gets logged?

βœ… Answer: 2
Because of lexical scope, inner() remembers the a defined in its outer environment.


πŸ” Hoisting in JavaScript

🚨 Hoisting = Declarations are moved up during compilation

console.log(name); // undefined

var name = "Ali";

 

console.log(age); // ❌ ReferenceError

let age = 25;

var is hoisted (with value undefined)
let is hoisted but in the Temporal Dead Zone (TDZ) until initialized


πŸš€ Real-World Challenge #2: TDZ Trap

function test() {

  console.log(a); // ???

  let a = 10;

}

test();

βœ… Answer: ReferenceError
Why? let was hoisted but not initialized β€” it's in the Temporal Dead Zone.


πŸ”’ Closures β€” Functions That Remember

A closure is when a function β€œremembers” variables from its outer scope β€” even after that outer scope has finished executing.

πŸ” Closure Example

function counter() {

  let count = 0;

  return function () {

    return ++count;

  };

}

 

const increment = counter();

console.log(increment()); // 1

console.log(increment()); // 2

βœ… count stays in memory thanks to the closure


πŸš€ Real-World Challenge #3: Custom Counter Using Closure

// Implement this function:

const counter = createCounter();

 

console.log(counter()); // 1

console.log(counter()); // 2

console.log(counter()); // 3

βœ… Solution:

function createCounter() {

  let count = 0;

  return function () {

    return ++count;

  };

}


πŸ” Closure in Loops β€” The Classic JS Bug

for (var i = 0; i < 3; i++) {

  setTimeout(() => console.log(i), 1000);

}

// Expected: 0 1 2

// Actual: 3 3 3

βœ… Fix 1: Use let (block scoped):

for (let i = 0; i < 3; i++) {

  setTimeout(() => console.log(i), 1000); // βœ… 0 1 2

}

βœ… Fix 2: Use closure (IIFE):

for (var i = 0; i < 3; i++) {

  (function (x) {

    setTimeout(() => console.log(x), 1000);

  })(i);

}


πŸš€ Real-World Challenge #4: Closure in DOM Event Handlers<button id="btn0">Button 0</button>

<button id="btn1">Button 1</button>

<button id="btn2">Button 2</button>

for (var i = 0; i < 3; i++) {

  document.getElementById(`btn${i}`).addEventListener("click", function () {

    console.log(i); // ❌ Always logs 3

  });

}

βœ… Fix it using a closure:

for (var i = 0; i < 3; i++) {

  (function (index) {

    document.getElementById(`btn${index}`).addEventListener("click", function () {

      console.log(index);

    });

  })(i);

}

βœ… Or just use let:

for (let i = 0; i < 3; i++) {

  document.getElementById(`btn${i}`).addEventListener("click", function () {

    console.log(i);

  });

}


βœ… Summary

Concept

Key Takeaways

Scope

Determines variable visibility and lifespan

Hoisting

Variables/functions declared early but initialized later

TDZ

Accessing let/const before initialization throws error

Closures

Functions keep memory of outer variables after execution

Real Usage

Used in counters, timers, event handlers, private variables



Back

FAQs


1. What’s the best way to prepare for JavaScript interviews?

Focus on the fundamentals: closures, scoping, async/await, and the event loop. Practice real code challenges, not just theory.

2. Is ES6 knowledge enough for interviews?

Mostly yes, but you also need to understand JavaScript’s core behaviors beyond just syntax β€” like prototype chains and hoisting.

3. Why are closures and scopes such common questions?

Because they reveal whether a developer understands how memory, function environments, and execution context work in JS.

4. Do interviews test JavaScript beyond the browser?

Yes. Even full-stack roles often involve Node.js questions, but core JS concepts are always in play.

5. How important is async programming in interviews?

Very. Interviewers often test your ability to handle real-world async flows β€” promises, async/await, and the event loop.

6. Should I memorize definitions or practice solving problems?

Practice! Understand the why and how behind behaviors β€” interviews often involve debugging or refactoring.

7. Are array methods like .map() and .reduce() really asked?

Yes β€” often in coding challenges or refactor tasks to test clean, functional thinking.

8. Do I need to know prototypal inheritance?

Absolutely. You should understand how prototypes work and how classes build on top of them.

9. What tools should I use for practicing JavaScript interviews?

Platforms like LeetCode, CodeSignal, JSFiddle, and browser DevTools are great. Pair with actual coding in VS Code for muscle memory.

10. What’s the #1 mistake devs make in JS interviews?

Rushing to code without fully understanding the problem. Many JS bugs come from misunderstanding scope, context, or async behavior.

Tutorials are for educational purposes only, with no guarantees of comprehensiveness or error-free content; TuteeHUB disclaims liability for outcomes from reliance on the materials, recommending verification with official sources for critical applications.