Why does ++ increment after returning the value in this JavaScript code?

43 views Asked by At

Here's the problem (with a working solution):

Create a function cycleIterator that accepts an array, and returns a function. The returned function will accept zero arguments. When first invoked, the returned function will return the first element of the array. When invoked a second time, the returned function will return the second element of the array, and so forth. After returning the last element of the array, the next invocation will return the first element of the array again, and continue on with the second after that, and so forth.

My question is in regards to line 7.

function cycleIterator(arr) {
    let indexCounter = 0;

  return function() {
    
    if (indexCounter >= arr.length) indexCounter = 0;
    return arr[indexCounter ++];    //WHY IS THIS [O, 1, 2] NOT [1, 2, 3]
  }
}

// Uncomment these to check your work!
const threeDayWeekend = ['Fri', 'Sat', 'Sun'];
const getDay = cycleIterator(threeDayWeekend);

console.log(getDay()); // should log: 'Fri'
console.log(getDay()); // should log: 'Sat'
console.log(getDay()); // should log: 'Sun'
console.log(getDay()); // should log: 'Fri'
1

There are 1 answers

0
Tarazed On

indexCounter++ Will increment after it's read. ++indexCounter Will increment before it's read.