What is a closure in JavaScript?
A
A function that returns another function
B
A function that has access to its outer function's scope even after the outer function has returned
C
A function that runs only once
D
A function that is stored in an object
Analysis & Theory
A closure is a function that remembers variables from its outer scope, even after the outer function has finished execution.
What will this output?
```js
function outer() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = outer();
console.log(counter());
console.log(counter());
```
D
`undefined` and `undefined`
Analysis & Theory
Each call to `counter()` remembers the `count` variable and increments it using closure.
Which of the following best describes why closures are useful?
A
They prevent memory leaks
B
They allow private variables
D
They remove all variables from scope
Analysis & Theory
Closures allow functions to keep variables private and persistent.
Which of the following is a closure?
A
`function add(x, y) { return x + y; }`
B
`let x = function() { return 1; }`
C
`function outer() { let x = 10; return function() { return x; }; }`
Analysis & Theory
That function keeps access to `x` even after `outer()` returns β itβs a closure.
What does this return?
```js
function makeMultiplier(x) {
return function(y) {
return x * y;
}
}
const double = makeMultiplier(2);
console.log(double(5));
```
Analysis & Theory
`double(5)` is `2 * 5 = 10`. The returned function remembers `x = 2`.
Which concept allows closures to remember variables?
Analysis & Theory
Closures use **lexical scoping**, meaning they remember the scope where they were defined.
What happens when you call a closure multiple times?
A
It resets all variables
B
It forgets outer variables
C
It keeps the state between calls
Analysis & Theory
Closures keep the values of captured variables even between calls.
What is the output?
```js
function init() {
var name = 'JavaScript';
function display() {
return name;
}
return display;
}
const fn = init();
console.log(fn());
```
Analysis & Theory
`display()` closes over `name` and returns it β a classic closure example.
Why do closures help create private variables?
A
Because they use `var` instead of `let`
B
Because variables are inside the global scope
C
Because the variables exist only inside the closure and are not directly accessible from outside
D
Because `this` binds them
Analysis & Theory
Closure variables are not accessible from outside β they are private to the returned function.
How can closures cause memory issues if not managed properly?
A
They never release memory
B
They keep references to outer variables, which may prevent garbage collection
C
They remove variables too early
D
Closures are only available in ES6
Analysis & Theory
Closures maintain references to outer scopes, which can cause memory leaks if not cleaned up properly.