Why does this code works while this does not?

Question - Given the array arr , iterate through and remove each element starting from the first element (the 0 index) until the function func returns true when the iterated element is passed through it.

Then return the rest of the array once the
is satisfied, otherwise, arr should be returned as an empty array.

My code which fails the test -(similiar to this, since I tried the solution code given on freecodecamp so i made minor changes to that)

function dropElements(arr, func) {
  
  for(let i = 0; i < arr.length; i++){
  if(func(arr[0])){
    break;
  }
  else{
    arr.shift();
    }
  }
  return arr;
}

dropElements([1, 2, 3], function(n) {return n < 3; });

Solution code

function dropElements(arr, func) {
  var times = arr.length
  for(let i = 0; i < times; i++){
  if(func(arr[0])){
    break;
  }
  else{
    arr.shift();
    }
  }
  return arr;
}

dropElements([1, 2, 3], function(n) {return n < 3; });

Hello there,

With this line:

var times = arr.length

times is a snapshot of the length of arr. So, for(let i = 0; i < times; i++){ is constant.

Whereas, for(let i = 0; i < arr.length; i++){ keeps changing, as arr is being modified with arr.shift().

Hope this helps

3 Likes

Oh I see. Thanks a lot.