Seek and Destroy Arguments Object Question

Seek and Destroy Arguments Object Question
0.0 0

#1

Hi all,

I have found a solution to this challenge now (see code below). What I don’t understand is why I have to assign arguments[i] to a variable to get it to work. I was trying before to test the argument directly in the return statement (return (ele != arguments[i])) but that didn’t work. Could anyone explain to me why this is? Thanks!

function destroyer(arr) {
  for (var i = 1; i < arguments.length; i++) {
    var num = arguments[i];
       arr = arr.filter(function(ele) {
         return (ele != num);
       });
  }
  return arr;
}

Link to the challenge:


#2

Guesswork

Could have to do with the way filter() behaves. I tried to use Array.forEach() a certain way once because I thought it just was a for loop on an array, until I tried something that didn’t work and read the way it uses the callback isn’t the same as I’d get using a normal for loop.

I’m just speculating here and I don’t remember what I tried to use the forEach() for. I just learned that those methods don’t always do what you think they do. There is no reason you can’t accomplish this assignment using the regular methods you learned though. Just declare an empty array and push all values that are not found.

Edit

Okay it appears to be a closure issue. If you console.log inside your filter method, the arguments object will contain the arguments passed to your anonymous function, the callback, which is the current index of the array you’re performing an operation against. All the filter method is trying to do then is say if x !== x, which does nothing.

This is to be expected, arguments are initialized in the closure of each function, they’re what store all the parameters passed in. Even if you’re not declaring a new arguments object, all functions do this themselves.