% 2 === 1 on filter prototype section

Can someone explain why at the bottom of the challenge “item % 2 === 1” returns as true for the numbers NOT divisible by two? I thought === 1 meant true. So wouldn’t that mean that, for example, 23 % 2 should not return since it is not divisible by 2? Or am I thinking about this all wrong? I got the challenge completed thanks to a youtube video, but this part is really stumping me. Thank you so much in advance!!

  **Your code so far**
// The global variable
const s = [23, 65, 98, 5];

Array.prototype.myFilter = function(callback) {
// Only change code below this line
const newArray = [];

for (let i = 0; i < this.length; i++) {
  if (callback(this[i])) {
    newArray.push(this[i]);
  }
}
// Only change code above this line
return newArray;
};

const new_s = s.myFilter(function(item) {
return item % 2 === 1;
});

console.log(new_s);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36

Challenge: Implement the filter Method on a Prototype

Link to the challenge:

Modulus is commonly used when checking if a value is an odd number or even:

return 22 % 2 === 0;
/*this returns true because 22
 is an even number.*\

return 23 % 2 === 1;
//this returns true because 23
 is an odd number.

Why would it not return? Since you’re not comparing the result to 0 or 1, it will not return a boolean, instead, it will return a value. Which is 0.46

Hello :wave:

You appear to be misinterpreting the result of your check — don’t worry, it’s a very easy mistake to make :slight_smile:

When you do your check, 23 % 2 === 1, what you are asking JS to do is, “divide 23 by 2, and take the remainder. If it is strictly equal to 1, return True.” However, remark that if the remainder of the check is 1, then the number is not even — it is odd. Hence, you are asking JS to return True if, and only if, the check number is odd.

If you would like JS to return True when the number is even, as you expected to happen, you can instead write, 23 % 2 === 0. In this case you are asking JS, “divide 23 by 2, and take the remainder. If it is strictly equal to 0 (in other words, it’s even), return True.”

In this particular case, 23 is odd so, as expected, 23 % 2 evaluates to 1. It follows that 23 % 2 === 0 will evaluate to False, which, because we specifically arranged the check to allow so, can be interpreted to mean the number is not even and so is odd.

I hope this helps!

Good luck with your adventures in JavaScript :blush:

1 Like

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