dictionary of days of the month zero indexed in javascript

You can create a zero-indexed dictionary in JavaScript to map the days of the month as follows:

index.tsx
const daysInMonth = {
  0: 31,
  1: 28,
  2: 31,
  3: 30,
  4: 31,
  5: 30,
  6: 31,
  7: 31,
  8: 30,
  9: 31,
  10: 30,
  11: 31
};
134 chars
15 lines

Here, each key-value pair represents the zero-indexed month number and its corresponding number of days. For example, 0 represents January which has 31 days, and hence the value for key 0 is 31. Similarly, October (which is the 9th month when indexed from 0) has 31 days, and hence the value for key 9 is 31.

You can access the number of days in a particular month using the zero-indexed month number as follows:

index.tsx
const month = 1; // February (which has 28 days in a non-leap year)
const days = daysInMonth[month];
console.log(`Number of days in month ${month + 1}: ${days}`); // Output: Number of days in month 2: 28
204 chars
4 lines

In this example, the variable month is set to 1, which represents February. We then access the corresponding value in the daysInMonth dictionary using the zero-indexed month number as the key. The resulting value is then stored in the days variable and printed to the console.

gistlibby LogSnag