Iterate forwards or backwards in a for loop
- tags
- #Javascript #Coding
- published
It is trivial to write a for loop that counts upwards or that counts downwards, but what if you want to go upwards some of the time and downwards the rest of the time? Sure, you could use a function and switch between two different for loops each with the same function inside, but that’s not quite as elegant as what I’m about to show you today.
Normally, to count upwards, you start your loop at 0 and count up to the final
element of the array. To count downwards, you start at the final element of the
array and count down to 0. For this loop, though, we will always start at 0 and
count either up or down. If we count up, we’re done after that. But if we count
down, we end up with negative values for i, which aren’t any good. That’s why
we create a new value of ix, which is offset upwards by one less than the
array length only if we are counting downwards. We use this value of ix
wherever we would normally use i inside the loop.
Here’s what the code looks like:
const someArray = [1, 7, 9, 3, 4, 8, 0];
const upwards = true;
const direction = upwards ? 1 : -1;
for (let i = 0; Math.abs(i) < someArray.length; i += direction) {
let ix = upwards ? i : i + (someArray.length - 1);
let value = someArray[ix];
console.log(value);
}
Or, you know, you could just reverse the array before the loop.