frenchie
frenchie

Reputation: 52017

javascript date reference or value

I'm storing a date in a global variable called MyDate. If I write this:

var TheDate = MyDate;

for (var i = 5; i > 0; i--) {
   TheDate = TheDate - i;
}

Am I just changing TheDate or am I also changing MyDate?

Thanks.

Upvotes: 2

Views: 1355

Answers (4)

Aminesrine
Aminesrine

Reputation: 2140

you can simply check it

var TheDate = MyDate;
for (var i = 5; i > 0; i--) 
{
   TheDate = TheDate - i;
   alert("TheDate = " + TheDate);
   alert("MyDate = " + MyDate);
}

Upvotes: 0

Kshitij
Kshitij

Reputation: 8634

It will only change TheDate.

see this fiddle link

This is because when you do TheDate = TheDate - i TheDate is no more treated as Date object but instead is long.

Upvotes: 5

emphaticsunshine
emphaticsunshine

Reputation: 3775

Objects are by reference so it will change both of the variables.

Upvotes: 0

silly
silly

Reputation: 7887

if MyDate is a Object: yes, if is a scalar: no

Upvotes: -2

Related Questions