Endless for loop when using array.length

Viewed 916

Randomly encountered this. When I store array.length in a variable and apply to the for loop condition using operator <= the loop works fine but when I use array.length with the same operator it becomes infinite.

function map(array, callback) {
  let k =array.length;
   for(let i= 1; i<=k; i++)
     {
      array[i] = callback(array[i]);
     }

    return array;
}
console.log(map([1, 2, 3], addTwo));

This works as expected. But when I use this

   function map(array, callback) {

    for(let i= 1; i<=array.length; i++)
     {

     array[i] = callback(array[i]);
     }

    return array;
    }
     console.log(map([1, 2, 3], addTwo));

Of course i=0; i<array.length; is the way to do it. But I am curious what's happening inside it.

2 Answers

In the first case the variable with the length does not change, but in the second, you take the length directly and this change.

let k = array.length;

keeps a length until the iterator reaches an index greater than k.

The other one

for (let i = 1; i <= array.length; i++)
//                 ^

takes the actual length and while the index is compared against the length adds one index to the array for every call at the end of the original array.

You can easily see what happens if you add a console.log in there:

let addTwo = x => x + 2

function map(array, callback) {
  for (let i = 1; i <= array.length; i++) {
    console.log(i, array.length)  // <-- print out i and the length of the array
    array[i] = callback(array[i]);
    if(i==5)  // <-- so we do not run out of memory
     return false
  }
  return array;
}
console.log(map([1, 2, 3], addTwo));

Bottom line is you are saying that the for loop should keep going as long as i is less or equal to the array.length but at the same time once i reaches the actual length of the array we continue to increase both. i via i++ and array.length via array[i] = callback(array[i]); so there is no end in sight.

Related