The modulus operator (%) finds the remainder after the division of two numbers. For example, 3 divided by two results in a quotient of 2 and a remainder of 1.
console.log(3 % 2); // 1
11 divided by 4 results in a quotient of 2 and a remainder of 3.
console.log(11 % 4); // 3
All even numbers have a remainder of 0 when they're divided by 2.
4 % 2; // 0
6 % 2; // 0
8 % 2; // 0
10 % 2; // 0
All odd numbers have a reminder of 1 when they're divided by 2.
5 % 2; // 1
7 % 2; // 1
9 % 2; // 1
11 % 2; // 1
The modulus operator is a great way to determine if a number is odd or even.
Question | Click to View Answer |
What does the following code print to the console? console.log(9 % 4);
|
1 9 divided by 4 has a quotient of 2 and a remainder of 1. |
What does the following code print to the console? console.log(31 % 2);
|
1 If the divisor is 2, the modulus operator will always return 1 for odd numbers. |
What does the following code print to the console? console.log(16 % 2);
|
0 If the divisor is 2, the modulus operator will always return 0 for even numbers. |