Infinite loop question - Seek and Destroy

So I am not specifically asking about this challenge because I know the solution but I am trying to better understand certain methods to get to a solution.

This code below is what I am playing with but i get a warning for a possible infinite loop on line 7.
for (var j = 1; j < arguments.length; j++) seems to be the culprit, but I can’t see how this is an infinite loop, unless I am just getting myself confused which is quite possible, can anyone lend an explanation as to why I get that warning.

Thanks

Your code so far

function destroyer(arr) {
  // Remove all the values
  var newArray=[];
  
    for (var i = 0; i < arr.length; i++) {
      
      for (var j = 1; j < arguments.length; j++) {
        
        if (arguments[j] == arr[i]) {
            newArray = arr.push(arr[i]);
          
        }                         
        
      }
      
    }
     
  return newArray;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36.

Link to the challenge:

Hey there,
Looking at it briefly I suspect the issue is this line.
newArray = arr.push(arr[i]);
in particular arr.push(arr[i]);
This pushes arr[i] to arr,
Thus in the line for (var i = 0; i < arr.length; i++) , the arr.length continues to grow in length thus creating an infinite loop.

if you wanted to push arr[i] into newArray, it should be newArray.push(arr[i]);

1 Like

Ahhhh thanks, i was focusing on checking the actual for loops rather than my code.
That makes sense, let me have a look at it again.

Thanks for the quick response.

Rule of thumb: do not modify an array you are iterating over.