JavaScript Pointers and Dates - javascript

I noticed this situation in my code (unfortunately), and was able to duplicate it in my own JS file. So I have this code:
var date1 = new Date(); // today
var date2 = date1;
date2 = date2.setDate(date2.getDate() + 1);
// what is date1?
After this code executes, date1 is today's date + 1! This harkens back to my undergrad days when I learned about pointers, and I guess I'm a little rusty. Is that what's happening here? Obviously I've moved the assignment away from date1, and am only modifying date2, but date1 is being changed. Why is this the case?
Incidentally, after this code executes date2 is a long number like 1272123603911. I assume this is the number of seconds in the date, but shouldn't date2 still be a Date object? setDate() should return a Date object.

Classic case of Rerence Types vs. Value Types.
When the assignment operator works on
primitive values (numbers, strings,
Boolean, null, and undefined), a copy
of the value is made. When the
assignment operator works on
JavaScript objects, references to the
objects are copied.
Assignment by Value Versus Assignment by Reference
Therefore:
// creates a new Date object in memory with date1 as a Reference to its location
var date1 = new Date();
// date2 will now point to the same Object in memory as date1
var date2 = date1;
// Since both date1 and date2 point to the same object,
// modifying one changes the other
date2 = date2.setDate(date2.getDate() + 1);
As for the resulting value, you're correct. It's getting converted inside the expression to the number of seconds since Epoch.

Your variables date1 and date2 are pointing to the same object.
That's why the when you execute the setDate on the date2 variable, you see the change on date1, because actually the two variables point to the exact same object.
_____ ____________
|date1| --------->| new Date();|
¯¯¯¯¯ ¯¯¯¯¯^¯¯¯¯¯¯
_____ |
|date2| -----------------
¯¯¯¯¯
The setDate method returns the valueOf the Date object after changing it, which is a numeric representation, milliseconds since 01 January, 1970 UTC until your date.

both your variables reference the same object, and the setDate() call actually changes the object itself (in other words, it doesn't just clone the original and return the new one)
When you use a Date object in an expression it can end up being cast to a number, which (as you say) is the number of seconds since the epoch.

This code:
var date1 = new Date(); // today
var date2 = date1;
...creates one date object, which has two references to it. Since both variables point to the same object, any changes to the object are visible using either variable. They both point to the same thing. The thing stored in the variable is the reference to the object, not the actual object.
The best way to think about it (and indeed literally what's happening) is that variables contain values. Full stop. With primitives like (say) the number 5, the value held by the variable is the value. With object references, the value held by the variable is a reference to (pointer to) the object, not the actual object. For all we know, that reference is the number 77314 which is an index into some lookup table somewhere containing the actual object data. We don't know (or care), it's just a value that gets us to the object.
The rules for what happens with assignment, passing values into functions, etc., are identical in both situations — values are values. So:
var n1, n2;
n1 = 5; // n1 has the value 5
n2 = n1; // n2 now also has the value 5
And:
var d1, d2;
d1 = new Date(); // d1 has a value that references the new Date object
d2 = d1; // d2 now also has that value, which references that object
When you change the object's properties, it doesn't have any effect on the reference to the object. The object's properties belong to the object, not to the reference to the object. So since the two variables point to (refer to) the same thing, if you change that thing using one of the variables, you see the changes if you query the object using the other variable.

Related

javascript setMonth() - setting a month to date2 from date1. Why also date1 change?

I know, title isn't probably clear, but I have this code:
var date1=new Date();
alert(date1);
var date2=date1;
alert(date2);
date2.setMonth(date1.getMonth() + 6);
alert(date1+" - "+date2);
Why date1 change? I think date1 should remain the current date and date2 six months later ...
Thanks
Dates are objects in JavaScript. When you set date2=date1, both date1 and date2 will reference the same object. Since they are both references to the same date object, the object may be updated or inspected using either.
Both the variables are pointing to same date object. You can do this instead
var date1=new Date();
alert(date1);
var date2=new Date(date1.valueOf());
alert(date2);
date2.setMonth(date1.getMonth() + 6);
alert(date1+" - "+date2);
In this approach, I am creating new object using values of existing one. Now there are two objects being point by different variables.
While you had assigned same object to both variables.
Because date2 gets the reference to date1, not value.

Convert integer to Date in node.js

I'm trying to convert a integer to a Date using node .js, and Date.
I know that this is a very common question but all the solutions that have been posted before have failed to help me.
I am getting the dates from a json file found at http://api.guardian.gg/chart/elo/4611686018432537994,
Example date: 1461110400000
What I've tried:
var date = String(new Date(elodata.x));
and
var date = String(new Date(parseInt(elodata.x)));
But I get invalid date as a result.
I realise that this might not be doable because I don't know how guardian.gg handles this data. But you never know.
You can pass in your value directly to a Date constructor in Javascript if it is an integer (which it appears to be in :
var date = new Date(elodata.x);
Likewise, you can also use the the setTime() function in Javascript to pass your integer value in if you already have an existing object :
var date = new Date();
d.setTime(elodata.x);
Example
var d1 = new Date(1461110400000);
console.log(`Constructor: ${d1}`);
var d2 = new Date();
d2.setTime(1461110400000);
console.log(`setTime(): ${d2}`);
When a single argument is passed to the Date constructor, if it's a string it will be parsed. The result of that is implementation dependent but if 1461110400000 is a string it will almost certainly give an invalid date.
If given a number, it's treated as a time value. So if you're passing a number, make sure it's type number:
var timeValue = '1461110400000';
console.log( new Date(+timeValue));
You could also use Number(timeValue) or parseInt(timeValue) but unary + is less to type.

Why is it possible to subtract Date objects in javascript? Is there any form of operator overloading?

Why is the below code actually working?
Code
var firstDate = new Date();
// some time passing here
var secondDate = new Date();
// Difference seems to contain difference in miliseconds.
var difference = secondDate - firstDate;
What I get is, I believe, an equivalent to secondDate.getTime() - firstDate.getTime(). The only question is, how can this conversion to number of milliseconds happen in background? Is this some sort of operator-overloading?
The operator - converts the operands to numbers (check for example "12"-3). The date object defines a numeric conversion .valueOf() that returns the number of milliseconds.
See also for example +(new Date).

Creating a new Date object or using setter methods of javascript Date()

If I am going to be using Date() to generate dates and use its methods in my script should I create a Date() object once and re-use it or just create a new instance each time?
Is it more efficient\faster to do this:
var1 = new Date(2014, 5, 3)
var2 = new Date(2013, 2, 30)
var3 = new Date(2015, 10, 2)
or this:
myDate = new Date()
myDate.setDate(3)
myDate.setMonth(5)
myDate.setYear(2014)
var1 = myDate
myDate.setDate(30)
myDate.setMonth(2)
myDate.setYear(2013)
var2 = myDate
myDate.setDate(2)
myDate.setMonth(10)
myDate.setYear(2015)
var3 = myDate
Edit: my question wasn't very clear, let me try to explain:
I'm only using the Date() object for its methods and generating dates- meaning I don't really need a bunch of Date() objects just one I can use to do one-off operations like generate some date and call a method like toJSON() or something on it. After I generate the date and call the method I don't need a persistent object hanging around because I won't be doing anything with it. Would it consume less resources to reuse one Date() object like this or is it even slower?
Another edit:
I was thinking I could also put it in a function so I'd be doing this:
myDate = new Date();
setDate = function(dateObj,day,month,year) {
dateObj.setDate(dat);
dateObj.setMonth(month);
dateObj.setYear(year);
return myDate;
}
var1 = setDate(myDate,12,10,2014);
Anything value in doing it like this?
Your examples are two different things. The first example creates three separate Date objects, which can have three different dates.
The second example creates one Date object, which var1, var2, and var3 point to. When you change the Date object, var1, var2, and var3 will all see that change.
new Date is a constructor. it is written in javascript. In OO programming you usually don't replicate code. So if you have a constructor new Date() - which you have in JS, and setters, it is most likely that doing new Date(2013, 2, 30) is equivalent to:
var myDate = new Date();
myDate.setDate(30);
myDate.setMonth(2);
myDate.setYear(2013);
according to this, the allocation alone will cost you and the second way you presented is faster.
BUT (!!!) the two ways don't give the same results. In the first you gain three different objects. in the later you get only one.

What does this javascript variable mean?

When I create variables I don't use brackets after equal sign.
Why does this code use brackets after equal sign? Can anyone explain this? I want to know what does it mean after equal sign.
var start = (new Date).valueOf(),
The paranthesis around new Date cause that to be evaluated first, so the date is created, and THEN call valueOf on the newly created date.
It's basically like doing
var d = new Date();
var start = d.valueOf();
but on one line.
However, it should be (new Date()).valueOf(). What is there right now will error out.
the intention of this is to shorten the following code:
var date = new Date();
var start = date.valueOf();
but you can't write:
var start = new Date().valueOf();
because theres no Date().valueOf() that can be used as constructor, so you'll have to add braces. the part in braces will be executed first (creating a new date), and valueOf() will be called on the result of the code in braces (read: on the constructed date). That said, the solution is what we got in your question:
var start = (new Date).valueOf();
the result of all this is a timestamp in milliseconds.
This method returns the equivalence of the Date object in milliseconds.
The milliseconds are expressed as an integer representing the number of milliseconds between midnight January 1, 1970 (GMT) to the date and time specified in the Date object.
Easy thing. new Date returns a date. Without brackets, it would be new Date.valueOf(). Since Date doesn't have a method valueOf(), this results in an error.
BUT, an instance of Date has this function. So we use brackets. (new Date).valueOf() is the same as
var start = new Date;
start.valueOf();
The wrapping parens around new Date evaluates the call to create a Date object then calls a method of the date object -> valueOf. An easier to understand example would be
(3 + 2) + 2; // = 7 - evaluates 5 then adds 2
the valueOf method is defined as:
Returns the primitive value of a Date object. Overrides the Object.prototype.valueOf method.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
You can actually achieve the same thing by
var start = +(new Date())
// returns the integer value of the date (in milliseconds)
// aka the primitive value

Categories