Question about intermediate javascript for loops

Tell us what’s happening:

Can anyone tell me why its necessary to create the “times” variable here to store the arr.length?
couldnt:
for (var i = 0; i < times; i++)
just be:
for (var i = 0; i < arr.length; i++)
?
Thank you!
Your code so far


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

// test here
dropElements([1, 2, 3, 4], function(n) {return n >= 3;})

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it

Because arr.length is changing inside the loop
In this way times stores the length of the original array

If you want to check inside the loop as last line add this:
console.log("'times' is " + times + ", 'i' is " + i + " and 'arr.length' is " + arr.length + ".\nAnd 'i < arr.length' is " + (i < arr.length) + " but 'i < times' is " + (i < times) + ".")

Try with the various test cases and you will see that with arr.length it wouldn’t work.

Okay, that makes sense!

can you move this to js section, that’s for js, click edit title

1 Like