Hi @sethdcd,
Here is a complete explanation of everything that is happening in that code. I hope it helps answer your question.
First let’s look at the statement destroyer([1, 2, 3, 1, 2, 3], 2, 3);
this calls a function named destroyer
and passes it 3 arguments:
The first argument is the Array [1, 2, 3, 1, 2, 3]
The second argument is the Number 2
The third argument is the Number 3
Now let’s look at the body of our destroyer
function. The first statement inside that function is:
args = arguments;
This statement creates a variable named args
and assigns it to a value that represents an array-like object of all of our arguments. In this particular example, it’s roughly the equivalent of writing:
args = [[1, 2, 3, 1, 2, 3], 2, 3]
So args
is an Array-like object that contains 3 values:
The value at index 0 is the Array [1, 2, 3, 1, 2, 3]
The value at index 1 is the Number 2
The value at index 2 is the Number 3
Next, we return the result of evaluating the expression arr.filter(...)
arr
is the first parameter passed to the destroyer
function which, in this case, we know is the Array [1, 2, 3, 1, 2, 3]
filter
is a built-in function of the Array type which takes a callback function as its parameter and calls that function with each value of the array. If the callback returns true
, the current value remains in the array, if the callback returns false
, the current value is deleted from the array.
You can learn more about the filter
function on MDN by clicking here.
The callback passed to the filter
function is an anonymous function that reads as follows:
function(val) {
for ( i = 1; i < args.length; i++ ) {
if ( val == args[i]) {
return false;
}
}
return true;
}
This function says for every value of i
from 1 to 1 less than the total number of arguments:
- test the current value of the
arr
Array against the argument at the i
position of the args
Array-like object.
- if the current value of the
arr
Array is equal to the value of the argument at the i
position of the args
Array-like object, remove it from arr
Array, otherwise, keep it.
To see this illustrated more clearly, let’s consider the following call to destroyer
destroyer(['A','B','C'],'C','D')
Now let’s step through the calls to our anonymous callback function substituting in real values.
Since arr
contains 3 values A
, B
, and C
the callback function will be called 3 times, once for each value A
, B
, and C
. Here is what each of those calls is doing:
// 1st call
if 'A' equals 'C' return false
otherwise, if 'A' equals 'D' return false
otherwise, return true
// 2nd call
if 'B' equals 'C' return false
otherwise, if 'B' equals 'D' return false
otherwise, return true
// 3rd call
if 'C' equals 'C' return false // because this is true, code will STOP here.
otherwise, if 'C' equals 'D' return false
otherwise, return true
Hope that helps. Let me know if you have any other questions.
Regards,
Bill Sourour
devmastery.com