Home > database >  Why the code provides the odd number from the array?
Why the code provides the odd number from the array?

Time:05-27

could you please help me understand why the following line result is [1,3]?

[1,3,6].filter( item => item % 2)

I was expecting to receive the even number from the array.

Many thanks!

CodePudding user response:

Filter checks for a boolean, 3 % 2 is equal to 1, which evaluates to true.

You want item % 2 == 0

CodePudding user response:

Even numbers are those numbers that are exactly divisible by 2.

The remainder operator % gives the remainder when used with a number. For example,

const number = 6;
const result = number % 4; // 2 

Hence, when % is used with 2, the number is even if the remainder is zero. Otherwise, the number is odd.

// program to check if the number is even or odd
// take input from the user
const number = prompt("Enter a number: ");

//check if the number is **even**
if(number % 2 == 0) {
    console.log("The number is even.");
}

// if the number is **odd**
else {
    console.log("The number is odd.");
}

ref : https://www.programiz.com/javascript/examples/even-odd

  • Related