What coding scenario would require use of the modulo operator?


#1

I understand it and how it works, but I'm curious about what its used for! I'm trying to imagine what situation would require that operator and I'm dying to know before I go any further! :wink: (clearly, i'm being impatient! Its like wanting to know how a movie ends during a movie! - i guess I should let it unfold and discover it in due time!)


#2

with the help of the modulo operators leap years can be calculated pretty easy:

year = prompt("enter a year: ");
if (year % 4 == 0){
  console.log("leap year");
}else {
  console.log("not a leap year")
}

quit useful if you for example want to build a calendar, you need to know which years a leap years. working example

This is just an example which came to mind, i am sure there are plenty more.

personally i would do:

year = prompt("enter a year: ");
if (year % 4){
  console.log("not a leap year");
}else {
  console.log("leap year")
}

but that might be slightly confusing.


#3

AND year % 100 !== 0 OR year % 400 === 0

var leapYear = function (year) {
    return year % 4 === 0 && year % 100 !== 0 || year % 400 !== 0;
};

 > leapYear(2000)
=> false
 > leapYear(1900)
=> true
 > leapYear(2004)
=> true
 > leapYear(1600)
=> false

#4

Any time we are dealing with a periodic function we can draw upon modulo. Take for instance the days of the week. How might we attach one to a date, given the day of the week the month starts on?

var days = {
    0: "Sunday",
    1: "Monday",
    2: "Tuesday",
    3: "Wednesday",
    4: "Thursday",
    5: "Friday",
    6: "Saturday"
};

var day = 0;
console.log(days[day % 7]);

var first_day_of_month = "Wednesday";
var offset = 0;
for (day in days) {
    if (days[day] === first_day_of_month) {
        offset = +day -1;
    }
}
console.log(days[offset]);
var date = 24;
console.log(days[(date + offset) % 7]);    // Friday

Very simplistic, of course.

The most common use we make of modulo in these courses is determining divisibility, and parity.

n % 2 === 0

when n is even (divisible by 2).

48 % 7 === 6

which means 48 is not divisible by 7.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.