Solve - getMonth() is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Mathilda Khoo

Solve - getMonth() is not a function Error #

The "getMonth is not a function" error occurs for multiple reasons:

  • not using the new operator when instantiating a Date object.
  • calling the getMonth() method on an object that's not a valid Date.
  • misspelling the getMonth method.
  • placing a second set of parenthesis when calling the method, e.g. new Date().getMonth()().

typeerror getmonth is not a function

Here are some examples of how the error occurs:

index.js
// ⛔️ did not use `new` operator const m1 = Date('Sept 24, 22 13:20:18').getMonth(); // ⛔️ did not spell `getMonth` correctly const m2 = new Date('Sept 24, 22 13:20:18').getmonth(); // ⛔️ added second set of parenthesis const m3 = new Date('Sept 24, 22 13:20:18').getMonth()(); // ⛔️ not calling getMonth on a valid date object const m4 = {}.getMonth();

In the first example, we did not use the new operator to create the Date object, which is what caused the error.

In the second example, we didn't capitalize the getMonth() method correctly.

In the third example, we added an additional set of parenthesis, which ended up trying to call the method on an integer.

The fourth example calls the getMonth method on an object that isn't a valid Date object.

To solve the "getMonth is not a function" error, make sure to only call the getMonth() method on a valid Date object, e.g. const m1 = new Date('Sept 24, 22 13:20:18').getMonth();. The getMonth method returns a zero based value representing the month of the date.

index.js
const m1 = new Date('Sept 24, 22 13:20:18').getMonth(); console.log(m1); // 👉️ 8

The getMonth method can only be called on a valid date object and returns an integer between 0 and 11, representing the month in the given date. For example, 0 is January and 11 is December.

If you need to get the current month, you don't need to pass anything to the Date() constructor.

index.js
const current = new Date().getMonth(); console.log(current);

Note that if you pass an invalid date to the Date() constructor, the getMonth method will return NaN (not a number).

index.js
const m1 = new Date('invalid').getMonth(); console.log(m1); // 👉️ NaN

You can console.log the value you are calling the getMonth method on and see if it's a valid Date object.

You should only be calling methods like getMonth on a valid Date object.
Use the search field on my Home Page to filter through my more than 1,000 articles.