Checking whether a variable is a date in JavaScript is not inherently difficult, but there are certain nuances and challenges that can arise due to the flexibility and dynamic nature of the language.
Using typeof
might not always provide the expected result. In this case, typeof
returns “object” which doesn’t specifically indicate that the variable is a Date object.
const now = new Date();
console.log(typeof now); // "object"
Also just because a variable is a date object doesn’t guarantee it’s a valid date. You may need further checks for valid date ranges or formats.
instanceof
operatorThe instanceof
operator is a powerful tool for determining whether an object is an instance of a specific class or constructor function. It tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object.
function isDate(variable) {
return variable instanceof Date;
}
const myDate = new Date();
console.log(isDate(myDate)); // true
const myNumber = 2024;
console.log(isDate(myNumber)); // false
const myString = "Hello";
console.log(isDate(myString)); // false
When working with iframes or different JavaScript environments (realms), instanceof
might not behave consistently. This is because the instanceof
relies on the prototype chain, and objects created in different realms may have different prototypes even if they represent the same built-in type.
This scenario is not a common situation in typical web development. It might occur in more complex setups involving iframes, web workers, or other advanced use cases where multiple JavaScript environments are in play.
Object.prototype.toString.call()
You can use the Object.prototype.toString.call()
method to get the internal class of a variable, and compare it with the string "[object Date]"
. This method is more reliable than the instanceof
operator, as it works across different contexts.
function isDate(variable) {
return Object.prototype.toString.call(variable) === '[object Date]';
}
const myDate = new Date();
console.log(isDate(myDate)); // true
const myNumber = 2024;
console.log(isDate(myNumber)); // false
const myString = "Hello";
console.log(isDate(myString)); // false
This approach is more robust and handles instances from different worlds, but it might be slightly less performant than instanceof
.