I was just playing with Date object and I observed this
- new Date() // returns Date object
- Date() // returns Date in string format
MDN - Date documentation confirms this
Note: Note that 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.
Tricky part is new Date returns the same result which new Date() returned ?
I tried the same experiment with a normal function,
function f() { console.log(' I am executed'); } new f I am surprised to see I am executed gets logged. I am trying to find out the reason why f is called when I did not use execution () operator. Can somebody explain me why new called the method ?
PS: I don't know what new f should have given to me. It was a syntax mistake So I thought it would give me an error. But It does not.
newoperator; it's as simple as that.newto work anyway? If notnew fwouldn't do anything at all becauseFunction, wouldn't be invoked and so no "new" function object would be created. Correct?newif you're not calling a function, in other words. I guess one should read anewexpression as, "I want to construct an object, and here's an expression that evaluates to a reference to the function I want you to call as the constructor." So calling the function is implicit. The slightly weird part is that if you want to call a function to provide the constructor, you have to parenthesize that.