Overview
Implement makeCounter(initialValue) that returns a function. Each call returns the current value and increments by 1.
Constraints
- The initial value is always an integer.
- The returned function takes no arguments.
Examples
const counter = makeCounter(5); counter(); // 5 counter(); // 6 counter(); // 7
Solution
Reveal solution
function makeCounter(initialValue) {
let count = initialValue;
return function() { return count++; };
}make-counter.js
Make Counter
easycodingJavaScriptClosures
Overview
Implement makeCounter(initialValue) that returns a function. Each call returns the current value and increments by 1.
Constraints
- The initial value is always an integer.
- The returned function takes no arguments.
Examples
const counter = makeCounter(5); counter(); // 5 counter(); // 6 counter(); // 7
Solution
Reveal solution
function makeCounter(initialValue) {
let count = initialValue;
return function() { return count++; };
}NameTopicDifficulty
103 of 103 problems