Reputation: 301
Yes i saw a lot of suggestions about similar topic and most of them didn't solve my question
here is a code from a book am trying to understand the work of the arrow function as am very used to the normal function... how can i write the below code with a normal function..
thank you
const schools = ["Yorktown", "Washington & Liberty", "Wakefield"];
const wSchools = schools.filter(school => school[0] === "W");
console.log(wSchools);
// ["Washington & Liberty", "Wakefield"]
i have tried in this way but not getting the result i want
const wSchools = schools.filter(function(school) {
school[0] === "W";
return school;
});
thank you in advance for a thorough explanation.
Upvotes: 0
Views: 110
Reputation: 786
Question has been answered, but the OP asked for understanding arrow functions, so let's go further now:
Arrow functions are simply functions that capture the scope of the current code block. It's super useful and I definitely encourage you to dig deeper in your understanding of these.
The particular form you encountered is the concise form where the body of the function can be reduced to a single return statement.
Take this regular function:
function(a, b) { return a === b }
It could be converted to this arrow function:
(a, b) => { return a === b }
But since our function only returns the result of a very simple test, we can make it shorter by straight out omitting both the curly braces and the return statement:
(a, b) => a === b
Nice and short, perfect for callbacks.
Here is some literature about arrow functions, hope you'll understand them better and get more comfortable using them, it will give you super powers :)
Upvotes: 0
Reputation: 521
Its super simple just change this
const wSchools = schools.filter(function(school) {
school[0] === "W";
return school;
});
To This
const wSchools = schools.filter(function(school) {
return school[0] === "W";
});
Explanation: This is the basic syntax of Arrow function according to MDN
param => expression
which can also be written as
(param) => { return expression }
Upvotes: 1
Reputation: 1640
You wrote the function correctly in terms of code correctness, but you have a logical error. You have to return a true or false when using an array filter.
const wSchools = schools.filter(function(school) {
return school[0] === "W";
});
Upvotes: 1