/Scope & Closures
Concept Detail

Scope & Closures

Difficulty: hard

Overview


Variable scope determines where a name is accessible. Global scope is accessible everywhere. Function (local) scope is limited to inside a function. Block scope (let/const) is limited to a {} block. The scope chain walks outward from inner to outer scopes to resolve names. A closure is a function that retains access to its outer scope even after that outer function has returned. Closures enable data encapsulation, memoisation, and the module pattern.

Practice Linked Questions


hard

Q1. What is the output? ```js function outer() { let count = 0; return function inner() { count++; return count; }; } const increment = outer(); console.log(increment()); console.log(increment()); ```


Select one answer before revealing.

hard

Q2. What is a closure in JavaScript?


Select one answer before revealing.

hard

Q3. What is the output of the classic closure-in-loop problem? ```js for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); } ```


Select one answer before revealing.

medium

Q4. What is variable scope in JavaScript?


Select one answer before revealing.

medium

Q5. Which of the following correctly describes a pure function? (More than one answer may be correct.)


Select one answer before revealing.

hard

Q6. What is the scope chain?


Select one answer before revealing.

hard

Q7. What is the output? ```js function outer() { var x = 10; function inner() { console.log(x); } return inner; } const fn = outer(); fn(); ```


Select one answer before revealing.

hard

Q8. What is the output? ```js function makeMultiplier(factor) { return (num) => num * factor; } const triple = makeMultiplier(3); console.log(triple(7)); ```


Select one answer before revealing.