Javascript Pointers question with Dates

Posted by Mega Matt on Stack Overflow See other posts from Stack Overflow or by Mega Matt
Published on 2010-04-23T15:41:42Z Indexed on 2010/04/23 15:53 UTC
Read the original article Hit count: 139

Filed under:
|
|
|

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...

Thanks for the help.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about pointers