July 13, 2000 - JavaScript Calendar | WebReference

July 13, 2000 - JavaScript Calendar

Yehuda Shiran July 13, 2000
JavaScript Calendar
Tips: July 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

When you implement a function, always try to minimize the number of if statements. It helps the performance, of course, but more importantly it makes the function much more simpler to maintain. Take for example the following function that accepts the month of the year and the year, and returns the number of days in that month. The year is needed just for leap-year adjustment:

function getDays(month, year) {
  // create array to hold number of days in each month
  var ar = new Array(12);
  ar[0] = 31; // January
  ar[1] = (leapYear(year)) ? 29 : 28; // February
  ar[2] = 31; // March
  ar[3] = 30; // April
  ar[4] = 31; // May
  ar[5] = 30; // June
  ar[6] = 31; // July
  ar[7] = 31; // August
  ar[8] = 30; // September
  ar[9] = 31; // October
  ar[10] = 30; // November
  ar[11] = 31; // December
  // return number of days in the specified month (parameter)
  return ar[month];
}

The function stores in an array the count of days in each month, and then returns the proper element of the array.

This function is part of our Calendar application. To see further how we wrote it, go to Column 64, HTML Components.