34.
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Invoked Function Expression**
What is the output of the following code?
const func = (function () {
let counter = 0;
return function () {
return counter++;
}
})();
let result = func();
result = func();
result = func();
console.log(result);
Pick ONE option
Show answer & explanation
Answer: B. 2
The IIFE creates a closure that maintains a persistent counter variable initialized to 0. Each call to func() returns the current counter value and then increments it (post-increment operator). After three calls, result contains the return value of the third call, which is 2 (the counter's value before the third increment).
Step-by-step Derivation:
Execution trace:
- IIFE executes immediately, initializes counter = 0, returns the inner function
- func() called 1st: returns counter++ → returns 0, then counter becomes 1
- func() called 2nd: returns counter++ → returns 1, then counter becomes 2
- func() called 3rd: returns counter++ → returns 2, then counter becomes 3
- console.log(result) outputs: 2
Key concept: Post-increment (counter++) returns the value before incrementing, and the closure preserves counter across all function calls.