I'm more talking about how adding "new" affects the var, why/when it is used, and why i get the same answer when printing both?
-
3http://stackoverflow.com/questions/9584719/date-vs-new-date-in-javascript – Lain Dec 02 '16 at 21:05
-
1^... or the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date). – Teemu Dec 02 '16 at 21:06
1 Answers
In JavaScript, Date()
is what's called a "constructor function". Constructor functions are typically denoted (by convention) by starting with a capital letter. As such, the JavaScript developer is supposed to know when they see this to make an "instance" of the object that is constructed by the function.
When you write:
var d = Date();
You get a string value with the current date in it. But this is a literal value. You can't, for example, add 3 years to the date.
But, when you write:
var d = new Date();
You get back an Object that is manipulatable via properties and methods. So, you could write:
d.setFullYear(d.getFullYear() + 3);
Usually, we don't want the string. We want an object because it's dynamic and we can do more with it (including turning the date into a string).
The best rule of thumb is that when you see something that starts with a capital letter (a.k.a. Pascal Case), you should use new
with it and expect an Object back.
See this for more info. on the Date() object.

- 64,069
- 6
- 49
- 71
-
so just to clarify: adding new makes the var into an object which is in turn a set of multiple values? – Benjamin Malovrh Dec 05 '16 at 15:21
-
@BenjaminMalovrh Sort of. You will have an object, which in this case doesn't so much store multiple values, but that object provides a wide set of operations that you can perform on the data stored in the object. Different objects will store different data (many do store multiple values) and provide different sets of operations. – Scott Marcus Dec 05 '16 at 15:29