const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion'];
const filtered = cats.filter((cat) => cat.startsWith('L'));
console.log(filtered);
// [ "Leopard", "Lion" ]
In the above code,the argument passed into the arrow function (cat),is not defined any where in the code.
So, how does it gets executed and give us the correct result?
(Since cats is defined and cat is not , so i guess it should be cats which is passed to the arrow function)
However when i executed the above statement, it works fine,Can any one explain why?
Hello, Vaish!
So, first off the array function .filter()
accepts a function as an argument, which is the arrow function you are passing to it.
This function will walk your cats
array item by item, running that function for each of those items and returning an array including all the items where the function evaluated to true
(in this case, when your cats
species start with an L)
Now, the function that you pass as an argument to filter()
will already accept some arguments in order, and taking your code as an example:
// that function can use 3 arguments, named however you want, prepopulated with information from the item your filter() function steps in on each iteration.
// 1 value: the value of the item you are iterating
// 2 index: the index on the array of the item you are standing on
// 3 array: the whole original array you are walking
const filterFunction = (value, index, array) => { ... // does the stuff }
// those arguments are optional, but will be populated with those values in order, so, doing this:
const valueFilterFunction = (value) => value.startsWith('L')
// is equivalent to
const yourCatFilterFunction = (cat) => cat.startsWith('L')
I hope that helps! Link to the doc page on MDN: Array.prototype.filter() - JavaScript | MDN (mozilla.org)
2 Likes
Thank you so much @Arturo_Mosqueda, I really took my time in understanding the filter concept,I need to get more familiar with this.