Does not understand why these are the answears

Hello.
I started some online course not long ago where after every section there is a little test. In the test there is a section where i can’t understand the answear no matter how hard i try please someone explain it to me how it get those answear.
The codes are: [2, 4, 7].filter(item=>item%2)
[0, true, ‘Boo’].filter( item =>item)
[1, 3, 6].filter(item=>item%2)
Thank you for help in advance.

  • List item
const modArray = [2, 4, 7].filter(item=>item%2)
console.log(modArray);

The above returned this array: [7]

Per MDN:
array.filter: callbackFn (which is (item=>item%2)

Function is a predicate, to test each element of the array. Return a value that coerces to true to keep the element, or to false otherwise.

2%2 = 0 which is a falsy value; same for 4%2.
7%2 = 1 which a true value. So an array containing 7 was returned.

If I run this:

const modArray = [2, 4, 7].filter(item=>item%2 ===0)
console.log(modArray);

I get [2,4]

Thank you very much now i understand it completly.

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