Seek and Destroy issues

This code is not working:

function destroyer(arr) {
  // Remove all the values
  var result = arr;
  for (var i = 1; i < arguments.length; i++) {         
    result = result.filter(function(val) {
      return val != arguments[i]; 
    });
  }
  return result;
}

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

But when I assign the value of arguments[i] to another variable:
var arg = arguments[i];``` And usearg` instead, it works:

function destroyer(arr) {
  // Remove all the values
  var result = arr;
  for (var i = 1; i < arguments.length; i++) {   
    var arg = arguments[i];        
    result = result.filter(function(val) {
      return val != arg;
    });     
  }
  return result;
}

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

Can anyone explain such a behaviour?
Also, I get this warning:

Don’t make functions within a loop.

Which probably means I shouldn’t make functions within a loop :slight_smile:
Can someone explain this also.

In the first code snippet, the second arguments variable refers to the arguments passed to the second function you made (the one in the for-loop), not to the arguments of the destroyer function.

1 Like