Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
JavaScript for Frontend Interviews
  1. 1.Introduction to JavaScript & Setup
  2. 2.Variables and Data Types
  3. 3.Operators and Expressions
  4. 4.Control Flow: Conditionals
  5. 5.Control Flow: Loops
  6. 6.Functions: Basics
  7. 7.Arrays and Objects
  8. 8.Higher-Order Functions & Callbacks
  9. 9.Scope and Closures
  10. 10.`this` Keyword and Context
  11. 11.Asynchronous JavaScript: Callbacks & Promises
  12. 12.ES6+ Features (Part 1)
  13. 13.ES6+ Features (Part 2)
  14. 14.Error Handling & Debugging
  15. 15.Asynchronous JavaScript: Async/Await
  16. 16.Prototypal Inheritance & `new` Keyword
  17. 17.Event Loop, Microtasks & Macrotasks
  18. 18.Working with the DOM
  19. 19.Advanced Array Methods & Data Structures
  20. 20.Frontend Interview Prep & Best Practices
JavaScript for Frontend Interviews
09

JavaScript · Lesson 9 of 20 · 3 min

Scope and Closures

This is how you explain closures to prove you understand how JavaScript actually works.

After this lesson, you'll be able to explain the single most common closure-related interview question and articulate the trade-offs of using them, particularly regarding memory. This isn't just theory; it's the mechanism behind modern frontend component state and encapsulation.

How JavaScript Finds Your Variables

JavaScript has lexical scope. This means a variable's accessibility is determined by where you write your code, not where it runs. This creates a scope chain.

When you reference a variable, the engine first looks in the current function or block. If it's not there, it walks up to the parent scope, and so on, until it reaches the global scope. If it's not found there, you get a ReferenceError.

let and const create block scope (anything inside {}). var creates function scope. In an interview, always use let and const. Using var signals you're either unaware of modern JS or have a very specific, legacy-related reason you'd better be prepared to defend.

Using Closures to Create Private State

A closure is a function that remembers the environment where it was created. In practice, this means an inner function can access variables from its outer function, even after the outer function has finished executing.

This isn't magic. The inner function simply maintains a reference to its parent's scope. The most powerful application of this is creating private state, which is the foundation of the module pattern and how encapsulation is achieved in JavaScript.

function createCounter() {
  let count = 0; // This 'count' is private to the closure's scope

  return {
    increment: function() {
      count++;
      return count;
    },
    getCount: function() {
      return count;
    }
  };
}

const counter1 = createCounter();
console.log(counter1.getCount()); // 0
counter1.increment();
console.log(counter1.getCount()); // 1

const counter2 = createCounter(); // Creates a new, independent scope and 'count'
console.log(counter2.getCount()); // 0

// You cannot access 'count' directly.
// console.log(counter1.count); // undefined

Here, count is encapsulated. It can only be modified or read through the methods returned by createCounter. Each call to createCounter creates a new, independent scope with its own count variable.

The Classic Loop Interview Question

This is the most common closure-related problem you will face. It directly tests your understanding of scope.

The trap: An interviewer shows you this code and asks what it will log.

// The problematic 'var' version
for (var i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i);
  }, 10);
}

// The correct 'let' version
for (let j = 0; j < 3; j++) {
  setTimeout(function() {
    console.log(j);
  }, 10);
}

The first loop logs 3, 3, 3. The second logs 0, 1, 2. You must be able to explain why.

With var, there is only one i variable for the entire function scope. The setTimeout callbacks are all created within the loop, but they don't execute until the loop is finished. By then, i has a final value of 3. All three callbacks close over the same i variable, so they all log 3.

With let, the variable j is block-scoped. In each loop iteration, a new block scope is created, with a new j variable bound to that iteration's value. Each callback closes over its own unique j, preserving the value from that specific iteration.

Where Closures Cause Memory Leaks

Closures hold references to their outer scopes. This prevents the garbage collector from cleaning up those scopes, which can lead to memory leaks if you're not careful.

A long-lived closure can unintentionally keep large objects or DOM elements in memory. A classic example is an event listener on a DOM element. The callback is a closure. If you remove the element from the DOM but forget to call removeEventListener, you've created a leak. The listener (and its closed-over environment) still exists, preventing the element and its scope from being garbage collected.

This is why component-based frameworks have cleanup lifecycles (useEffect return function in React, ngOnDestroy in Angular). When a component unmounts, you must clean up its subscriptions, timers, and event listeners to release the memory held by their closures. Mentioning this shows you think about the entire lifecycle of your code.

Try it

Write a once function. It takes another function fn as an argument and returns a new function that will only call fn the first time it's invoked. All subsequent calls to the returned function should do nothing. Use a closure to keep track of whether fn has already been called.

Next: We'll cover how the value of a function's context is determined in "this Keyword and Context".

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Higher-Order Functions & Callbacks

Next

`this` Keyword and Context