Understanding the filter() function

Hello. I am having a lot of trouble understanding the filter() function. I have tried looking here also, but the explanation confused me. Array.prototype.filter() - JavaScript | MDN
So, I decided to look here.
How to use the JavaScript filter array method? - Flexiple Tutorials
In the example below, they use freelancer as a parameter, then they return freelancer.skill…I don’t understand how you can use .skill if freelancer is not an object above. Freelancers has the property of skill, but I don’t see how freelancer does?

let freelancers = [{name: "Harry", skill: "JavaScript"},{name: "Mark", skill: "Python"},{name: "David", skill:"JavaScript"}];

let javascript_freelancers = freelancers.filter(function(freelancer) {
    return freelancer.skill == "JavaScript"; });

console.log(javascript_freelancers);

//Output = [{ name: "Harry", skill: "JavaScript" }, { name: "David", skill: "JavaScript" }]

If anyone could break down the filter() function for me, I’d really appreciate it (: Very confusing topic lol.

Not quite. The function returns the following:

freelancer.skill == "JavaScript";

This is a boolean statement that returns either true or `false.

The function you pass into filter needs to return a boolean value so that filter knows whether to keep a particular item in the array or not. filter is passing each item in the array freelancers into the function you passed into filter. If that function returns true then you keep the item, otherwise you throw it out.

1 Like

Thanks for the explanation. I just don’t understand the function(freelancer) part. freelancer is a parameter, but I’m just trying to understand how that filters

Filter is basically going over every element from an array, similar to how you would use a normal for loop. When it gets an element its then passing it to the provided function, which like @bbsmooth said has to return either a true to keep the element, or false to toss it. So in this case freelancers is an array, and in that array the elements are objects with key/value pairs. So the function that is passed to filter as you know has the parameter freelancer, and because the array is full of objects freelancer becomes those objects because filter is tossing the array elements to the provided function. And you can get the value of there properties the same way you would any other object, with dot notation if you know the key name.

So in this case all we care about are these people with the skill of JavaScript, so freelancer.skill works perfectly fine.

If you check out the Functional Programming section of the JavaScript curriculum, there’s a couple modules on filter early on, including one where you implement filter itself from scratch.

Ok so in THIS case, with the filter function, the RETURN is not literally printing anything ---- it’s saying “if this is true”, keep it

return never print, return establish what is the function output