0

why do I need to use the keyword new when using Date().

var currentDate = new Date();
console.log(currentDate);

but if i just do the below I can still get the date.

console.log(Date()); 
  • [This](https://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript) question may be useful. – VedantBang May 08 '20 at 16:41
  • because date() in constructor of JavaScript, so when you call any constructor you have to use new keyword for Date objects. – Bhavik Hirani May 08 '20 at 16:43
  • Hello, the `new` keyword before any variable -> class declaration gives us the ability to work with the `this` variable and it points directly to the newly created object( The class itself ). – Adnane Ar May 08 '20 at 16:45
  • @BhavikHirani nothing in that statement is correct. `Date` is an object literal and can be called without new. https://css-tricks.com/understanding-javascript-constructors/#article-header-id-4 – max May 08 '20 at 16:47
  • `new` is the operator to create object instances in JavaScript—nothing weird here. The peculiarity here is that `Date` is coded to additionally have a function call form... which does not return a date instance at all but a mere string. – Álvaro González May 08 '20 at 17:41

1 Answers1

0

The new keyword does the following things:

  1. Creates a blank, plain JavaScript object
  2. Links (sets the constructor of) this object to another object
  3. Passes the newly created object from Step 1 as the this context
  4. Returns this if the function doesn't return its own object

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

Quinn Keaveney
  • 777
  • 11
  • 31