Confused with this array.filter() method

I am learning filter() method. From what I have learnt about it is, this is a method that is being applied to each array element and return a array consisting of elements that satisfy condition/logic being provided in the callback function.

const array = [1,2,3,4,5,6,7,8,9];
var resultArray = array.filter(x=>{return x>6});
console.log(resultArray)//[7,8,9]

The confusing part is when the arrow function executes x>6, shouldn’t it be returning true rather than the value of x itself?
Shouldn’t the output of the be like this

console.log(resultArray) //['true','true','true']

Have a look at this function

function check(n){
return n>4;
}
console.log(check(6));//return true which is expected

Then what is happening with that x>6 inside the callback function.

I think that you have a small misunderstanding.

Any of the array elements where the callback return true are kept, with their values unchanged. A filter isn’t a map, and it doesn’t change values like a map.

1 Like

You’re correct in saying that return x > 6 should return true or false if you were using it in a regular function that you made yourself.

But, .filter() is not a regular function, it’s an array method.

What are array methods, anyway?

.filter() is one of a bunch of array methods that come with JavaScript.
Some others include .map() , .every() , .reduce()

Array - JavaScript | MDN – a full list can be found here under ‘Instance Methods’ if you’re interested.

You’ll become more familiar with them as you go through the course, so don’t worry if they seem a little confusing at first.

Why do we use them?

Basically, to save time & do more with less code.
There are some common things that developers frequently want to do to arrays, so instead of typing them out by hand every time we can make use of some pre-made functions that JS gives us for free!

So why is ‘return x > 6’ not behaving how we expect?

Just imagine that JS is taking that x > 6 and putting it inside of an if statement, running that if statement on each element in the array, and then sending back an array with only the elements that are larger than 6.

Since array methods are all about saving us time and writing less code, it makes sense that we don’t see that if statement or the for loop that goes over the array,
since that would take much more time then using the handy .filter() JS gives us.


Hope I’ve explained that ok. Let me know if you have any other questions! :slight_smile:

2 Likes

Thank you for clearing my misunderstanding.

Thank you for elaborating all the details. I was little confused. You did a great job explaining in detail.

1 Like

you can always grant the user a “solution” tag, for his detailed and useful answer, as a sign of gratitude :slight_smile:

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.