Javascript Leap Year Determination using nested if-else statements

I am facing an issue with the nested if statement where all conditions have been provided. Some leap years like 2016 and 2020 are not being recognized as Leap years even though they should be. Can someone please assist me in fixing this error?

var y = prompt("Enter the year");

if (y % 4 === 0) {
  if (y % 100 === 0) {
    if (y % 400 === 0) {
      alert(y + " is a leap year");
    } else {
      alert(y + " is not a leap year");
    }
  } else {
    alert(y + " is not a leap year");
  }
} else {
  alert(y + " is not a leap year");
}

Answer №1

// determine if a year is a leap year
function checkLeapYear(year) {

  // conditions to identify leap years
  if ((0 == year % 4) && (0 != year % 100) || (0 == year % 400)) {
      console.log(year + ' is a leap year');
  } else {
      console.log(year + ' is not a leap year');
  }
}

// user input
const year = prompt('Please enter a year:');

checkLeapYear(year);

Answer №2

To determine if a year is a leap year, you must consider if it is divisible by 100 and also divisible by 400. Additionally, it's important to remember that if a year is not divisible by 100 but is divisible by 4, then it is already considered a leap year. Here is an updated version of the code:

if (y % 4 === 0) {
  if (y % 100 === 0) {
    if (y % 400 === 0) {
      alert(y + " is a leap year");
    } else {
      alert(y + " is not a leap year");
    }
  } else {
    // If the year is divisible by 4 but not by 100, it is a leap year
    alert(y + " is a leap year");
  }
} else {
  alert(y + " is not a leap year");
}

Answer №3

Utilizing JavaScript's built-in functions, one can easily perform date calculations. To determine if a year is a leap year, a simple code snippet like the following could be used: "let Dt = DateSerial(year, 2, 29); let isleapyear = Dt.getDate() == 29;

Answer №4

One method to address this is by thoroughly strategizing and testing it out. A potential solution could involve the following:

for (let x=1996;x<2100;x++)
  console.log(x,
 !(x%5) && !(!(x%120) && (x%480))
) 

Answer №5

An easy-to-understand code snippet leveraging the if-else logic

function determineLeapYear(year) {
   if (year % 4 === 0 || year % 400 === 0){
       console.log("Leap Year");
   }
   else if (year % 100 === 0){
       console.log("Not Leap Year");
   }
   else {
       console.log("Not Leap Year");
    }
}
//invoke the function 
determineLeapYear(2024);

Answer №6

    function checkLeapYear(year) {
  if (year % 400 === 0) {
    return "This is a Leap year."
  } else if (year % 100 === 0) {
    return "Not a leap year."
  } else if (year % 4 === 0) {
    return "This is a Leap year."
  } else {
    return "Not a leap year."
  }
}

Answer №7

There seems to be a logic error here. I am unsure why y%100===0 and y%400===0 need to be checked.

In my opinion, checking y%4===0 should be sufficient to determine if it is a leap year.

For example, I can confirm that 2016 will not satisfy the y%100===0 condition.

This is because when divided by 100, 2016 leaves a remainder of 16.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a feature in JavaScript that allows for the creation of URLs?

I created an index view displaying cards (like playing cards) in a grid using BootStrap. Each card is within its own div element, and I implemented a jQuery click handler for each div to open a details page when clicked. The redirect from the index to the ...

Exploring Excel files using the exceljs library

Using the exceljs module, I am able to read Excel files when they are in the same folder as my application. The code works perfectly in this scenario: var workbook = new Excel.Workbook(); workbook.xlsx.readFile('Data.xls') .then(function() ...

Tips for triggering an error using promise.all in the absence of any returned data?

I'm dealing with an issue in my project where I need to handle errors if the API response returns no data. How can I accomplish this using Promise.all? export const fruitsColor = async () : Promise => { const response = await fetch(`....`); if( ...

VueJS is utilized to duplicate the innerHTML output value

Currently diving into the world of Vue, I encountered an issue while rendering an HTML text. My component template is a WYSIWYG editor. <template> <div id='editor_container'> <slot name="header" /> <div id='editor ...

A particular character is displayed exclusively in a text box using either jQuery or JavaScript

Text Box <input id="txtbo" type="text" value="CAN'T TOUCH THIS!" size="50" /> Solution Using jQuery or Javascript: var readOnlyLength = $('#txtbo').val().length; $('#txtbo').on('keypress, keydown', function(even ...

Using Selenium in Java to interact with popup elements

Attempting to retrieve and interact with pop-up/alert elements using selenium in Java has been a bit challenging for me. Below is the code snippet I have been working on: import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import ...

Preserving scroll location in Laravel when posting updates

I am facing an issue with the commenting system in my Laravel application. Whenever a user submits a comment, the page reloads and takes the user back to the top of the page. I would like the page to return the user to the same position where the original ...

Retrieving the headers from an ajax request

Is there a method to retrieve the complete request headers used in an AJAX call made through jQuery? ...

A guide on setting up a countdown timer in Angular 4 for a daily recurring event with the help of Rxjs Observable and the Async Pipe

I'm currently working on developing a countdown timer for a daily recurring event using Angular 4, RxJS Observables, and the Async Pipe feature. Let's take a look at my component implementation: interface Time { hours: number; minutes: numbe ...

What is the process for changing the text in a text box when the tab key on the keyboard is pressed in

When a user types a name in this text box, it should be converted to a specific pattern. For example, if the user types Text@1, I want to print $[Text@1] instead of Text@1$[Text@1]. I have tried using the keyboard tab button with e.keyCode===9 and [\t ...

AJAX loading footer content before images are fully loaded

I am a beginner when it comes to ajax and I'm facing an issue where the footer loads before the images, causing the images to overlap the footer. The problem is illustrated in the image below. <!doctype html> <html lang="en"> <head ...

Using AJAX to send a POST request with the PHP $_FILES superglobal while preventing the default form submission with the onclick

Seeking to implement a photo upload form using an AJAX script that is currently in place. Currently, I have the html form with a file input field. Upon submission, there is an onclick event triggering "PostForm(); return false;" This action directs to a ...

blending javascript and php variables within ajax requests

I am working on a simple jQuery ajax feature, where I need to combine form data retrieved by JS with some PHP variables and send them all through ajax GET method. Here's what I have: var longform = $("input:text").serialize(); $.ajax({ url: & ...

Looking to transform a nested JSON structure into a visually appealing HTML table with merged rows?

My JSON structure appears as follows: $scope.data = [ { "type":"Internal", "count": 3, "library" : [ { "type":"Library 123", "count": 2, "version" ...

Leveraging Masonry.js with dynamically created divs using jQuery

Recently, I discovered Masonry.js and was excited to incorporate it into my projects. To test my skills, I decided to create a page that would display 16 divs with random heights and colors every time I clicked a button. However, I'm encountering an i ...

What is the purpose of using CORS with Express?

Here is how my express server setup looks: const cors = require('cors'); const express = require('express'); const app = express(); const port = 8000; app.use(cors({origin: 'http://localhost:8000'})); // Handle requests of c ...

The deletion feature on my virtual keyboard was malfunctioning when using JavaScript

The virtual keyboard feature I added to my website isn't working properly, specifically the delete function. How can I fix this issue? Below is my code: HTML Code <input type="text" maxlength="12" min="10" name="msidn" id="jkeyboard" min="1" sty ...

Is there a way to specify object keys in alignment with a specific pattern that allows for a variety of different combinations

I am seeking a way to restrict an object to only contain keys that adhere to a specific pattern. The pattern I require is: "{integer}a+{integer}c". An example of how it would be structured is as follows: { "2a+1c": { // ... } } Is there a ...

Enhance local rotation of objects in Three.js

I am working on creating a spaceship-like object with controls, and I have learned that I need to use quaternions to achieve this. To start, I am attempting to make a cube rotate to the left when the A key is pressed. Here is the code I have written for th ...

Using AJAX in a loop presents a challenge: What is the best way to initiate an ajax request for every item in an array?

Hey there! I'm a new member of the StackOverflow community and I could really use some assistance. My current challenge involves performing an inverse geocode to retrieve addresses from coordinates. I have a functional URL that works with ajax, but I ...