Solve - Cannot read property 'getTime' of Undefined in JS

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

banner

Photo by Nicole Geri

Solve - Cannot read property 'getTime' of Undefined #

The "Cannot read property 'getTime' of undefined" error occurs when the getTime() method is called on an undefined value. To solve the error, make sure to only call the getTime method on date objects.

cannot read property gettime of undefined

Here is an example of how the error occurs.

index.js
const date = undefined; // โ›”๏ธ Cannot read properties of undefined (reading 'getTime') console.log(date.getTime());

To solve the error, initialize the value to a date object, or conditionally check that the value is of the correct type before calling the Date.getTime method.

index.js
const example = undefined; // โœ… Provide fallback value const date = example || new Date(); console.log(date.getTime()); // ๐Ÿ‘‰๏ธ 1638011.... // โœ… Using `if/else` if (date) { const result1 = date.getTime(); } else { console.log('date is falsy'); } // โœ… Using ternary const result2 = date ? date.getTime() : new Date().getTime(); // โœ… Provide fallback in place const result3 = (date || new Date()).getTime();

The first example shows how to use the logical OR (||) operator to provide a fallback value if the value to the left is falsy (e.g. undefined).

If the value to the left is falsy, the logical OR (||) operator returns the value to the right.

The next example uses a ternary operator, which is very similar to an if/else statement.

If the value to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise the value to the right of the colon is returned.

The last example uses the logical OR (||) operator to provide a fallback of a date object right before calling the getTime() method.

Conclusion #

The "Cannot read property 'getTime' of undefined" error occurs when the getTime() is called on an undefined value.

To solve the error, make sure to only call the method on date objects.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee