Hi there, dear community!
I was trying to do this JS exercise. Its orders are to write a JavaScript program to determine whether a given year is a leap year in the Gregorian calendar. This is, a “calculator” that meets the following conditions:
- If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
- If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
- If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
- The year is a leap year (it has 366 days).
- The year is not a leap year (it has 365 days).
So I go ahead and create a piece of code such as
let year;
const isLeapYear = year => {
if (year < 100) {
if (year % 4 === 0) {
return "a leap year."
} else {
return "not a leap year."
}
} else if (year === 100) {
return "not a leap year."
} else if (year > 100 && year < 400) {
if (year % 4 === 0 && year % 100 != 0) {
return "a leap year.";
} else {
return "not a leap year.";
}
} else if (year === 400) {
return "a leap year.";
} else if (year > 400) {
if (year % 4 === 0 && year % 100 != 0) {
return "a leap year.";
} else {
if (year % 400 === 0) {
return "a leap year.";
} else {
return "not a leap year.";
}
}
}
}
and I add a bit of a for
loop to check results:
for (let i = 0; i <= 2200; i++) {
console.log([i] + ' ' + 'is' + ' ' + isLeapYear(i));
}
which leads me to believe I’ve been fully successful at solving the exercise.
First of all, a side-order question: Why is the variable that I’ve declared at the very beginning completely useless? I mean, if I remove it, the code seems to continue working all finely…
Now, when I go ahead to have a look at the provided solution, I find:
function leapYear(year) {
return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
}
…which make me cry. Haha. My code is so freaking long and this is just three lines long
Now, my question would be about the exact interpretation that the computer makes out of that code (ternary conditionals, right?). I guess it is something like:
If year
is divisible by 100, the statement is true
, so check it to see if it’s also divisible among 400. In case it’s divisible both among 100 and 400, the statement is definitively true
. Otherwise, it’s false
. Then, if it is false
, check to see if it’s divisible among 4. If it is divisible among 4, then it’s also true
.
Something like that, perhaps? Anyway, I am gonna have to go back so that I can get familiarized with ternary operator, since it is obvious I haven’t learn 'em as properly as I should’ve
At MDN, I saw that syntax was
condition ? exprIfTrue : exprIfFalse
I guess that I had never imagine that “expression if true” and “expression if false” could indeed be another conditional expression, but I guess that that makes a whole lot of sense
Anyways, thanks again in advance, dear community, for whichever your possible answers! And Merry Christmas!
Cheers!