How to useTernary Operator in Javascript
Ternary operator (?:) is a shorthand conditional operator that evaluates a condition and returns one of two expressions based on the result.
Syntax:
condition ? value if true : value if false
Example: In this example, we are using the Ternary operator to find given number is even or odd.
function checkOddOrEven(num) {
return num % 2 === 0 ? 'Even' : 'Odd';
}
console.log(checkOddOrEven(21));
console.log(checkOddOrEven(12));
Output
Odd Even
JavaScript Program to Check if a Number is Odd or Even
We are going to learn how to check whether the number is Even or Odd using JavaScript. In the number system any natural number that can be expressed in the form of (2n + 1) is called an odd number and if the number can be expressed in the form of 2n is called an even number.
In other words, Those numbers that are completely divisible by 2 (give the remainder 0 after dividing by 2) are known as even numbers and those which divided by 2 and leave a reminder 1 are called odd numbers.
Even = {2k : k ∈ Z}
Odd = {2k + 1 : k ∈ Z}
where k is an integer.
Example:
Input: 2
Output: Even number
Input: 41
Output: Odd Number
There are several methods that can be used to Check if a Number is Odd or Even, which are listed below:
Table of Content
- Approach 1: Using the modulo Operator
- Approach 2: Using Bitwise & Operator
- Approach 3: Using Bitwise OR Operator (|)
- Approach 4: Using Ternary Operator