why do Date()
and new Date()
give different results? How is Date()
implemented and why is it implemented like this?
typeof(Date())
>> "string"
typeof(new Date())
>> "object"
why do Date()
and new Date()
give different results? How is Date()
implemented and why is it implemented like this?
typeof(Date())
>> "string"
typeof(new Date())
>> "object"
How is Date() implemented ?
There are some ways for a function to determine wether it was called with new
, one is checking the value of this
and another one would be new.target
(pseudocode):
function Date() {
if(!(this instanceof Date)) {
return "string";
}
}
However the internal objects are usually not written in JS itself, but rather in the language running JS.
and why is it implemented like this?
You will never get an answer to that. No one made bad design decisions.
It is a documented behavior:
Note: JavaScript
Date
objects can only be instantiated by calling JavaScriptDate
as a constructor: calling it as a regular function (i.e. without thenew
operator) will return a string rather than aDate
object; unlike other JavaScript object types, JavaScriptDate
objects have no literal syntax.
You can find it in ECMAScript 1st edition already, from 1997 (https://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf):
15.9.2.8 Date()
A string is created and returned as if by the expression new Date ().toString()