How to solve toISOString is not a Function in JavaScript
In this tutorial, we are going to learn about how to solve the TypeError: toISOString is not a function in JavaScript.
When we use a ‘toISOString()’ method on a value which is not a data type date object we will get the following error in our console.
Here is an example, how the error occurs:
const value = Date.now();
console.log(value); // unix timestamp
console.log(value.toISOString());
Output:
"TypeError: value.toISOString is not a function
In the example above, we are getting the error because we are using the ‘toISOString()’ method on a data type integer.
To solve the “TypeError: toISOString is not a function”, make sure to call the toISOString() method on a data type date object or convert the given value to a valid date object before calling the toISOString() method on it.
Here is an example:
const value = Date.now();
const currentDate = new Date(value);
const result = currentDate.toISOString('en-US');
console.log(result);
Output:
"2023-09-13T23:16:28.035Z"
In the example above, first we converted the value to a valid date object then, we have called the toISOString() method on it. So, it returns the string representation of the current date in date string format. The The timezone is always UTC, as denoted by the suffix Z.
Type checking
To avoid the run time errors, we can also check the given datatype is a object or not before calling the toISOString() method on it.
Here is an example:
const value = new Date();
if(typeof value === 'object' && value !== null && 'toISOString' in value){
console.log(value.toISOString());
}else{
console.log('Given value is not a Date object');
}
Conclusion
The “TypeError: toISOString is not a function” error occurs, when we call a ‘toISOString()’ method on a value which is not Date object. To solve the error, convert the value to an date object before calling the toISOString() method on it or make sure to use the toISOString() method on a valid date objects.