Filter Arrays with filter !==5

Tell us what’s happening:

Hello everyone,

I am trying to understand why it uses !==5 instead of just saying… val===5 … or is it just preference in this situation.

The following code is an example of using filter to remove array elements that are equal to five:

array = array.filter(function(val) {
  return val !== 5;
});

Thanks

Your code so far

var oldArray = [1,2,3,4,5,6,7,8,9,10];

// Only change code below this line.

var newArray = oldArray.filter(function(val){
  return val < 6;
});

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/604.5.6 (KHTML, like Gecko) Version/11.0.3 Safari/604.5.6.

Link to the challenge:
https://www.freecodecamp.org/challenges/filter-arrays-with-filter

.filter will remove any value that does not return true for the given condition.

so val !== 5 will remove 5 from the array as 5 !== 5 returns false

the code is saying…
filter the array and return any values that are not equal to 5?
you could do if val === 5 ( cut it from the array) and return the resulting array…
this way is faster mebbe?

Another way of stating this, is the above code is an example of using filter to keep only the array elements that are not equal to 5.

It is easier for me to think about what filter keeps instead of what it is going to remove. While iterating through the values in the array, it will keep only the array elements where the returned value is true.

To be pedantic, it removes any element that returns a falsy value (so returning 5, "foo", etc. is just as good as returning true):

[0, 5, "foo", null].filter(function(el) {
  return el;
}); // [5, "foo"]

Good point, I hadn’t thought of using filter like that. I’m sure I will find a problem to use it on!

Thanks :slightly_smiling_face: