How to Fix ".toISOString is not a function" JavaScript Error?

#Why Does This Happen?

In JavaScript, the error ".toISOString is not a function" typically occurs when you try to use the toISOString() method on a value that is not a Date object.

For example, this can happen if you call the method on a date string:

const myDate = '2024-01-06';
// TypeError: myDate.toISOString is not a function
const isoDateString = myDate.toISOString();

Similarly, when attempting to use toISOString() directly on Date() when it's called as a function (as opposed to a constructor), it throws an error:

// TypeError: Date(...).toISOString is not a function
Date().toISOString();

This happens because when Date() is called as a function, it returns a string representation of the current date and time, and not a Date object. Since toISOString() is a method of the Date object, calling it on a string value results in an error.

Please note that the Date.prototype.toISOString() method was introduced in ECMAScript 5, so it could also be the case that your environment does not support the Date.prototype.toISOString() method.

#How to Fix the Issue?

The toISOString() method is a built-in method in JavaScript that is used to convert a Date object to a string representation of the date in the ISO format. Therefore, to resolve this issue, you can make sure of the following:

  1. Your environment supports the Date.prototype.toISOString() method, and;
  2. You are using the toISOString() method on a valid instance of the Date object.

For example, if you have a date string, you can create a Date object from it first, like so:

// ES5+
const myDate = new Date('2024-01-06');
const isoDateString = myDate.toISOString();

console.log(isoDateString); // 2024-01-06T00:00:00.000Z

If you want the current date and time in ISO format, you can create a Date object representing the current moment and then use toISOString(), like so:

// ES5+
const myDate = new Date();
const isoDateString = myDate.toISOString();

console.log(isoDateString);

You can also use it as a one-liner, in the following way:

// ES5+
console.log(new Date().toISOString());

This creates an instance of the Date object and immediately calls toISOString on it.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.