Search code examples
arraysfunctionreturn

what's the return of this function


Can someone please explain this code to me? How does JavaScript know which month it is if this code is not in a loop?

  var month_name = function (dt) {
    mlist = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December",
    ];
    return mlist[dt.getMonth()];
  };

Solution

  • Date.getMonth() returns the month of a Date object as a number between 0 and 11. This means the return statement accesses the index of the current month in the array and returns it. This works because JavaScript counts months starting at 0 not 1 like in "human" dates.