check if number is even in javascript

To check if a number is even in JavaScript, you can use the modulo operator (%). The modulo operator returns the remainder after division. If a number is even, it will have no remainder when divided by 2.

Here's an example code snippet that demonstrates how to check if a number is even in JavaScript using the modulo operator:

index.tsx
function isEven(number) {
  return number % 2 === 0;
}

console.log(isEven(2)); // true
console.log(isEven(7)); // false
console.log(isEven(-4)); // true
154 chars
8 lines

In this code snippet, we define the function isEven that takes a number parameter. The function returns true if the number is even, and false otherwise.

The function checks whether number % 2 equals 0. If it does, the remainder is zero and the function returns true. Otherwise, the remainder is not zero, and the function returns false.

We then call the isEven function with three different numbers to test the function's behavior. The console output shows that the function works correctly for each test case.

gistlibby LogSnag