0

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"
Cyker
  • 9,946
  • 8
  • 65
  • 93
  • 2
    [From MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date): *"JavaScript `Date` objects can only be instantiated by calling JavaScript `Date` as a constructor: calling it as a regular function (i.e. without the `new` operator) will return a string rather than a `Date` object; unlike other JavaScript object types, JavaScript `Date` objects have no literal syntax."* – Tyler Roper Nov 13 '18 at 19:06
  • I would say the first comment is the actual answer and should be submitted as an answer – Ruben Swieringa Nov 13 '18 at 19:09
  • Many built in "constructors" behave differently when called with `new` vs without. E.g. `String(42)` vs `new String(42)`. – Felix Kling Nov 13 '18 at 19:18
  • @felix but ... why? Who needs `String` objects? – Jonas Wilms Nov 13 '18 at 19:35
  • @Jonas: Nobody at all :P Maybe a side effect of having string (and number) *methods*. – Felix Kling Nov 14 '18 at 07:51

2 Answers2

2

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.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

It is a documented behavior:

Note: JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the new operator) will return a string rather than a Date object; unlike other JavaScript object types, JavaScript Date 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()

Steve Holgado
  • 11,508
  • 3
  • 24
  • 32
tevemadar
  • 12,389
  • 3
  • 21
  • 49