In the map() and filter functions(), is the iteration variable implicitly defined in it? or we can also explicitly define a variable to iterate through the array?
const numberArray = [1, 2, 3, 4, 5];
const res = numberArray
.map(number => number * 2)
.filter(number => number > 5);
console.log(res);
Regarding declaration of iteration variable in Maps and Filters, how we can define it?
2
Answers
The map and filter methods have the same parameters: element, index and reference to the source array. In your case you use only the first argument. You can give any name to the arguments, the main thing is to keep their order. Accordingly, you define «variable» names when you declare your arrow function inside map or filter. The variable represents the current element of the array at each iteration.
Example with other names:
First i would recommend you to read the doc first:
map, filter
The callback function implicitly defines the iteration variable number in the map and filter functions.
The callback function has 3 params:
element
The current element being processed in the array.
index
The index of the current element being processed in the array.
array
The array map() was called upon.
number
here is the first param,Maybe below is more obvious to you:
Regarding how to implement the map by yourself:
map
const numberArray = [1, 2, 3, 4, 5]