Reputation: 1
I am a newbie, am trying to understand how Set Date Method work in JavaScript. The first code gave me different result than the second, despite they look (similar), i don't know why!
// First example
var a = new Date();
a.setFullYear(2020);
console.log(a); //result = Fri Feb 14 2020 18:29:28 GMT+0100 (West Africa Standard Time).
// Second example
var a = new Date();
var b = a.setFullYear(2020);
console.log(b); //result = 1581702924396
// I don't know why they gave different value
Upvotes: 0
Views: 120
Reputation: 1522
In the first example when you say a.setFullYear(2020);
that value is not saved in a variable and the method does not change the value of the variable it is called by , a
, on its own. When you log a
in the console, it is logging new Date()
which will be the current datetime string that you see returned in that example. If you wanted the results of setFullYear logged in the console in this example, you should have saved the result of the method to a (like a = a.setFullYear(2020)
), or just logged the method in the console like: console.log(a.setFullYear(2020))
if you did not need to use it again later.
In the second example, you save the return value of a.setFullYear(2020);
to a variable, b
and then log that variable in the console. The setFullYear method returns the number of milliseconds between Jan 1 1970 and now, which is what you see logged. This millisecond count is very useful for easily comparing and storing dates.
Upvotes: 1