JavaScript for loop - using variable set to array.length rather than using array.length directly

JavaScript for loop - using variable set to array.length rather than using array.length directly
0.0 0

#1

Hi everyone,

I’ve just completed the ‘Drop It’ challenge (this one) but my for loop only worked correctly when I assigned a variable to arr.length and used that as the conditional, rather than using i < arr.length directly in the loop. I can’t understand why those two would produce different results?

The test that it failed on before using the variable was the one that should’ve returned an empty array. Tests which returned arrays with values worked fine.

Here’s the code that worked, using the variable:


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

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

Would anyone be able to explain why I had to use a variable for that to work?

Thanks a lot!


#2

Hi, @codedbyrob. In this problem you want to iterate through all elements of arr, so i < arr.length immediately comes to mind. But note that the for-loop modifies arr (i.e. remove elements), so for every iteration arr potentially gets shorter, and comparing i with arr.length that can get shorter per iteration, the for-loop won’t have a chance to iterate through all elements as intended. So we store that length in a variable so all elements are accounted for.

This is my code for comparison. It uses a while-loop, because I felt it's more appropriate than a for-loop.
function dropElements(arr, func) {
  // Drop them elements.
  while (!func(arr[0])) {
    arr.shift();
  }
  return arr;
}

Also, if you have

if (/*condition*/) {
  break;
} else {
  // more code
}

you can drop the else and the braces and reduce nesting.

for(var i = 0; i < length; i++){
  if (func(arr[0])) break; // you can keep the braces for the `if` part if you want
  arr.shift();
}

#3

@kevcomedia that makes so much sense, thanks very much for the really quick answer :slight_smile: very much appreciated!