Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jonathan Hamada
4,810 PointsHelp with Conditional (ternary) Operator
How do I write a function that determines whether a given year is a leap year? If a year is divisible by four, it is a leap year, unless it is divisible by 100. However, if it is divisible by 400, then it is.
So far I have only figured out how print true or false to document. I am trying to print all the the leap years from 1900 to 3000. Thank you!
function leapYear() {
for (var year = 1900; year < 3000; year++) {
x = (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
document.write(x + ' ');
}
}
leapYear()
2 Answers
Craig Watson
27,930 PointsNo problem Jonathan,
I have amended the answer a little to remove the else if statement as well as a little counter variable to see how many leap years there are in total between the two given years.
Happy coding.
Crag :)
Craig Watson
27,930 PointsHi Jonathan,
So I worked on this for a little while, it was tough to get my head around the math lol.
function leapYear( yearFrom, yearTo) {
var countYears = 0;
// Loop through the years given
for ( var year = yearFrom; year <= yearTo; year++ ) {
// Is the year divisable by 4 but not divisible by 100
if ( ( ( year % 4 ) === 0 ) && !( ( year % 100 ) === 0 ) || ( ( year % 400 ) === 0 ) ) {
// Print year
document.write( year + " </br>" );
countYears++;
}
}
document.write( "There are " + countYears + " leap years between " + yearFrom + " and " + yearTo );
}
leapYear( 1900, 3000)
I "think" this is correct, not sure on the quickest way to prove it mind.
Hope this helps :)
Craig
Jonathan Hamada
4,810 PointsThank you so much Craig. I was stuck on this for about an hour and half. Really helps!
Jonathan Hamada
4,810 PointsThat's how you do it, so the && ! is what i should of done, Thanks again
Jonathan Hamada
4,810 PointsJonathan Hamada
4,810 PointsVery neat, I'll have to study that. Thank You