Modulo Operator
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 13 of 77.
The modulo operator % tells you what's left over after dividing one number by another.
result = dividend % divisor- dividend: The number being divided.
- divisor: The number that divides the dividend.
- result: The remainder of the division.
For example,
result = 10 % 3Here, 10 is divided by 3. 3 goes into 10 three times, with a remainder of 1. So, result will be 1.
Usually modulo is used for checking if a number is even or odd:
- If a number is even, dividing it by 2 will leave a remainder of 0.
- If a number is odd, dividing it by 2 will leave a remainder of 1.
Challenge
BeginnerWrite a code that initializes three variables, a, b and c with the values 9, 2.6, and 11 (respectively).
After that, initialize the following variables:
dthat will hold the result ofamodulo2ethat will hold the result ofamodulo3fthat will hold the result ofcmodulo10
Check out the result and see how different dividends and divisors affect the result.
Cheat sheet
The modulo operator % returns the remainder after dividing one number by another:
result = dividend % divisorExample:
result = 10 % 3 // result is 1Common use case - checking if a number is even or odd:
- Even numbers:
number % 2returns 0 - Odd numbers:
number % 2returns 1
Try it yourself
// Type your code below
// Don't change the line below
console.log(`a = ${a}`)
console.log(`b = ${b}`)
console.log(`c = ${c}`)
console.log(`d = ${d}`)
console.log(`e = ${e}`)
console.log(`f = ${f}`)This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False