Skip to content
Home ยป JavaScript Exercise 25: Logical Operators

JavaScript Exercise 25: Logical Operators

function test() {
    let year;
    year = parseInt(prompt("Which year?"));
    if (!(year >= 2001 && year <= 2100)) {
        alert(`${year} does not belong to the 21st century.`)
    } else if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)) {
        alert(`${year} is a leap year and belongs to the 21st century.`)
    } else {
        alert(`${year} is not a leap year and belongs to the 21st century.`)
    }
}

JavaScript Exercise: Checking Leap Years and the 21st Century

Working with dates and calendar rules is a common task in software development. From scheduling applications to financial software, correctly determining whether a year is a leap year is essential for reliable date calculations.

In this JavaScript exercise, we develop a simple application that asks the user to enter a year, determines whether it belongs to the 21st century and checks whether it is a leap year.

This exercise introduces several important JavaScript concepts, including logical operators, conditional statements, the remainder operator, user input and template literals.

The JavaScript code

function test() {
    let year;
    year = parseInt(prompt("Which year?"));

    if (!(year >= 2001 && year <= 2100)) {
        alert(`${year} does not belong to the 21st century.`);
    } else if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)) {
        alert(`${year} is a leap year and belongs to the 21st century.`);
    } else {
        alert(`${year} is not a leap year and belongs to the 21st century.`);
    }
}

1. Retrieving user input

The application starts by declaring a variable called year.

let year;
year = parseInt(prompt("Which year?"));

The prompt() function displays a dialog box asking the user to enter a year.

Since prompt() returns a string when the user submits a value, the parseInt() function converts this string into an integer.

For example, when the user enters "2024", the application converts it into the numerical value 2024.

2. Understanding the 21st century

Contrary to what some people might expect, the 21st century did not begin in 2000. It began on January 1, 2001, and ends on December 31, 2100.

The following condition checks whether the entered year falls outside this range:

if (!(year >= 2001 && year <= 2100))

Three important logical and comparison operators are used here.

OperatorDescription
>=Greater than or equal to
<=Less than or equal to
&&Logical AND
!Logical NOT

The logical AND operator requires both conditions to be true. The logical NOT operator subsequently inverts the result.

For example, entering 1999 produces the following message:

1999 does not belong to the 21st century.

3. Understanding leap years

A regular calendar year contains 365 days. However, the Earth takes approximately 365.2422 days to complete an orbit around the Sun.

To compensate for this difference, the Gregorian calendar periodically introduces an additional day in February.

366 days

The Gregorian calendar defines three rules for determining whether a year is a leap year:

  • A year divisible by 4 is a leap year.
  • A year divisible by 100 is not a leap year.
  • A year divisible by 400 is nevertheless a leap year.

For example, 2000 was a leap year, while 1900 was not. Similarly, 2100 will not be a leap year.

4. Implementing the leap year algorithm

The following JavaScript condition implements these three calendar rules:

(year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)

The % operator is known as the remainder operator. It returns the remainder of a division.

For example:

2024 % 4    // 0
2026 % 4    // 2
2100 % 100  // 0
2000 % 400  // 0

The strict equality operator === checks whether the remainder equals zero, while the strict inequality operator !== checks whether it differs from zero.

The logical OR operator || allows the condition to evaluate to true when either of its two main expressions is true.

Leap year decision logic

The Gregorian calendar algorithm, independently of the century validation.

5. Displaying results with template literals

The application uses template literals to generate dynamic messages.

alert(`${year} is a leap year and belongs to the 21st century.`);

Template literals use backticks instead of conventional quotation marks. The ${year} expression inserts the value of the variable directly into the string.

This makes the code more readable than traditional string concatenation.

6. Testing the application

From a software testing perspective, this exercise provides an excellent opportunity to apply Boundary Value Analysis and Equivalence Partitioning, two fundamental software testing techniques covered by ISTQB.

InputWithin centuryExpected classification
2000NoOutside century
2001YesRegular year
2002YesRegular year
2024YesLeap year
2026YesRegular year
2028YesLeap year
2099YesRegular year
2100YesRegular year
2101NoOutside century

The year 2100 is particularly interesting because it is divisible by 4 but is not a leap year due to the century exception.

Another interesting observation is that no year within the 21st century is divisible by 400. Consequently, that particular part of the leap year algorithm cannot be exercised successfully within the permitted input range.

Extracting the leap year algorithm into a separate function would make it possible to test this condition independently.

7. Interactive demonstration

Try entering different years to see how the original JavaScript algorithm behaves.Enter a year

Check year

This demonstration reproduces the behaviour of the original code.

8. Potential improvements

Although the application correctly implements the calendar rules, there is room for improvement.

The parseInt() function accepts partially numerical strings. For example, entering "2024abc" results in the integer 2024. Invalid input can also result in NaN, which the current application incorrectly classifies as being outside the 21st century.

Implementing proper input validation would make the application more robust.

Additionally, since the value of year is never reassigned, the variable could be declared using const instead of let.

Separating the leap year calculation into a reusable function would also improve maintainability and facilitate automated software testing.

Conclusion

This JavaScript exercise demonstrates how a calendar calculation involves several fundamental programming concepts. By combining conditional statements, logical operators, comparison operators, the remainder operator and template literals, we can translate real calendar rules into a functional JavaScript application. The exercise also illustrates the importance of boundary conditions, input validation and testability. These considerations are essential not only when learning JavaScript but also when developing reliable, maintainable and professionally tested software.

Leave a Reply

Your email address will not be published. Required fields are marked *