Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm learning javascript and react and I don't understand why the function returns Array(0)

I would like to make a monthly schedule and have dates dynamically when I change the me and the year and here, to have the dates of the current me I did this function and I don’t understand why it returns me Array(0)




const [moisActuel, setMoisActuel] = useState(new Date())

const genererJoursDuMois = () => {
    const jours = []
    const debutDuMois = new Date(
      moisActuel.getFullYear(),
      moisActuel.getMonth(),
      1
    )
    const dernierJourDuMois = new Date(
      moisActuel.getFullYear(),
      moisActuel.getMonth() + 1,
      0
    ).getDate()

    for (
      let jour = new Date(debutDuMois);
      jour <= dernierJourDuMois;
      jour.setDate(jour.getDate() + 1)
    ) {
      jours.push(new Date(jour))
    }
    return jours
  }

const joursDuMois = genererJoursDuMois()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue in your code is the comparison in the for loop’s condition: jour <= dernierJourDuMois. Here jour is a Date object and dernierJourDuMois is an integer representing the last day of the month. You’re comparing two different types, which is why it doesn’t work as expected.

Instead, you should create a Date object representing the last day of the month, and compare jour with this Date object.

You can check out this code, I just changed a few lines:

const genererJoursDuMois = () => {
    const jours = []
    const debutDuMois = new Date(
      moisActuel.getFullYear(),
      moisActuel.getMonth(),
      1
    )

    // Changed this line to store the date object of the last day of the month, not just the day
    const dernierJourDuMois = new Date(
      moisActuel.getFullYear(),
      moisActuel.getMonth() + 1,
      0
    )

    for (
      let jour = new Date(debutDuMois);
      // Updated this line to compare jour (Date object) with dernierJourDuMois (also Date object)
      jour <= dernierJourDuMois;
      jour.setDate(jour.getDate() + 1)
    ) {
      jours.push(new Date(jour))
    }
    return jours
}
const joursDuMois = genererJoursDuMois()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading