Check if a number is odd or even using Javascript
There are multiple ways in Javascript to check if a given value is even or odd. We will be explaining the methods one by one in this post.
const value = 6;
const is_even = value % 2 == 0;
if (is_even) {
console.log("Value is an even number");
} else {
console.log("Value is an odd number");
}
Output
Value is an even number
We are finding the mod of a number after dividing it by 2. If the mod is equal to 0 then the number is even and if it does not equal to 0, the number is odd.
# Example 2
function check_value(value) { return value % 2 == 0 ? "even" : "odd"; }
console.log("Value 10 is: " + check_value(10));
console.log("Value 11 is: " + check_value(11));
console.log("Value 12 is: " + check_value(12));
console.log("Value 13 is: " + check_value(13));
console.log("Value 14 is: " + check_value(14));
Output
Value 10 is: even
Value 11 is: odd
Value 12 is: even
Value 13 is: odd
Value 14 is: even
Check if a number is even or odd using AND operator
We can also use the AND(&) operator of Javascript to check whether a given number is even or odd. We have created a function check_val here that will be taking the value as a parameter. Inside the check_val() function, we are using AND operator inside and returning odd or even based on the given value.
// Check if a number is even or odd using AND operator
function check_val(val) {
return (val & 1) ? "odd" : "even";
}
console.log("Value 10 is: " + check_val(10));
console.log("Value 11 is: " + check_val(11));
console.log("Value 12 is: " + check_val(12));
console.log("Value 13 is: " + check_val(13));
console.log("Value 14 is: " + check_val(14));
Output
Value 10 is: even
Value 11 is: odd
Value 12 is: even
Value 13 is: odd
Value 14 is: even
Using ES6
If you are creating your application using ES6 then you can check the number for odd and even values with one line of code.
const is_odd = val => val % 2 == 1;
console.log(is_odd(3));
console.log(is_odd(4));
Output
true
false
In the above code example, we have created a function is_odd using ES6. It takes the number as a parameter and returns true if the value is odd and false if the value is even.
- Lodash - Check if a number is within the Range(without if-else)
- How would you check if a number is an integer?
- Calculate square root of a number using javascript
- Simplest Way to Find the Smallest Number in an Array using JavaScript
- Find the Third Smallest Number in an Array using Javascript
- Using regex to validate a phone number in Javascript
- Check if a string is Palindrome or not using Javascript