What would you call x
in the following snippet?
Is it a parameter, a variable, both, or something else?
[1, 2, 3, 4].filter(x => x > 2 );
What would you call x
in the following snippet?
Is it a parameter, a variable, both, or something else?
[1, 2, 3, 4].filter(x => x > 2 );
That would be a parameter since it’s part of the function declaration. A function is being passed with a parameter x to array filter function.
If it helps to aid understanding, that code achieves the same as the following:
[1, 2, 3, 4].filter(function (x) {
return x > 2;
});
So yes, x is a function parameter.
Another way to approach this is that when arrow-notation has only one function parameter, the parenthesis are optional. Here is the arrow notation with the parenthesis.
[1, 2, 3, 4].filter((x) => x > 2);
For the same of clarity, I prefer to either put the function on a separate line:
[1, 2, 3, 4].filter(
(x) => x > 2
);
or to use a named variable for the arrow-notation function:
const greaterThanTwo = (x) => x > 2;
[1, 2, 3, 4].filter(greaterThanTwo);
In both cases, x being a parameter is easier to see and understand.
In hindsight, [1, 2, 3, 4].filter(x => x > 2);
is about the worst way to present the code, as all of the others above have larger benefits.
Ok, ta.
So imagine you had to describe what is going on in that snippet of code. Would it be fair to say:
The
filter
method applies an anonymous callback function to each of the elements in the array, whereby the value of each element is passed as a parameter to the callback function. Thefilter
method then constructs a new array of the values for which the callback returns a value that coerces totrue
.
Or can anyone else think of a more succinct / beginner-friendly way to put it?
Thanks, @Paul_Wilkins. It’s clear what the code does, but I’m trying to nail down the terminology for a SP book.
Meh! I might have been tempted to name the parameter num
, but it is a throwaway example and I think it is obvious what it does.I find the other examples slightly more jarring to read.
Hmm, I’ve seen that corerces to true
somewhere else before. Here it is, on the MDN filter page:
How about the following wording:
The
filter method tests each element in the array against the anonymous callback function. Elements for which that function gives a truthy value, are returned as a new array.
Awesome. Thank you!
Just to chime in. My understanding is that the ‘x’ in your callback is the parameter. The element being passed in is an ‘argument’.
I prefer that, it’s more declarative. It also has re-use.
Shoot! You are quite correct Thanks for pointing that out.
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.