Why this works and this doesn't

Why this works and this doesn't
0.0 0

#1

Hello guys, so I’m making this algorithm challenges and the Seek and Destroy got me quite confused.

So I was trying to access the function’s aruments through argument[x] where I would iterate through them in a for loop.
It didn’t work.
It started working when I transformed the arguments into an array. But when I tried to log arguments[x] (let x be any number) into console it worked.

So here is the correct code:

    function destroyer(arr) {
  // Remove all the values
  
   var args = Array.prototype.slice.call(arguments);
  
  var newArr = arguments[0].filter(function(val){
  
    for(var x = 1; x < args.length; x++){
      if(val == args[x]){
        return false;
      }
    }
    
    return true;
    
  });
  
  return newArr;

And this is the incorrect code:

    function destroyer(arr) {
  // Remove all the values
  
  var newArr = arguments[0].filter(function(val){  
  
    for(var x = 1; x < arguments.length; x++){
      if(val == arguments[x]){
        return false;
      }
    }
    
    return true;
    
  });
  
  return newArr;
}

My question is how come one works and the other doesn’t?


#2

I read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
and it should work if you change:

arguments[0].filter to arguments.filter

#3

But then I filter the arguments not the array don’t I?


#4

Here is why you always want to pull the values out of the Arguments Object and save them to a local variable instead of using arguments directly:

arguments always refers to the arguments of the containing function.
When you create (or call) a filtering function, inside that function arguments refers to the arguments of that filter function.

So in arguments[0].filter(function(val){... any use of arguments will refer to val.


#5

Thank you!! It bothered me so much. :blush: