Roll Call
Prompt
Write a function rollCall that takes an array of names and returns a function. Each time the returned function is called, it should log the next name. After all names have been called, it should log "All names have been called".
Playground
You need a variable that remembers which name to call
next. An index starting at 0 works well. Each call
logs the name at that index and bumps it up by one.
When index reaches the length of the array, there are no
more names to call. At that point, log the "All names have
been called" message instead.
Solution
Explanation
If you've solved the toggle question, this is similar but with an ending. Instead of cycling back to the beginning when you reach the last item, you stop and print a "done" message.
We use a closure to keep track of where we are in the list. The index variable starts at 0 and lives inside rollCall, but the returned function can still access and update it every time it's called.
Each call checks: is index still within the array? If yes, log the name at that position and move index forward. If no, we've run out of names, so log "All names have been called".
function rollCall(names) {
let index = 0;
return function () {
if (index < names.length) {
console.log(names[index]);
index++;
} else {
console.log('All names have been called');
}
};
}Notice that once all names are exhausted, every subsequent call logs the same message. The index stays at names.length (or beyond) and the else branch keeps firing. The function doesn't crash or reset, it just gracefully handles being called after the list is done.
This is the same closure + index pattern from toggle and once, just with a different end condition. In toggle, the index wraps around. In once, a boolean flag prevents re-execution. Here, the index stops at the end and switches to a fallback message.