Variable values changing based on Function Use (value vs reference)

Variable values changing based on Function Use (value vs reference)
0

#1

I believe I have a grasp on the idea between the difference of passing variables by value or reference. I’m just not sure how to put it into practice…

function moreDays(days,date){
    x = date.setDate(date.getDate() + days);
    return new Date(x);
    
}

const firstday = new Date('9/18/2018');
console.log(firstday); // console: Tue Sep 18 2018 00:00:00

const newday = moreDays(17, firstday);
console.log(newday); // Fri Oct 05 2018 00:00:00 ... - WORKS YAY!
console.log(firstday); // Fri Oct 05 2018 00:00:00 ... - This changed too.. noooooo

What can I do so that the varaiable firstday doesn’t change if I reference it in the function moreDays()?


#2

The getTime method is a way to create the new date and assign to another variable and then just use setDate method to change the new date to be returned.

function moreDays(days,date){
  var x = new Date(date.getTime())
  x.setDate(date.getDate() + days);
  return x;
}

#3

Because date.setDate() updates that date itself, then assigns that to x (which, by the way, you’ve made global).

… I tried to sneak my answer there JUST ahead of you, @RandellDawson, but you got FAST fingers. I’ll bet you sniped ebay auctions, back in the day. :wink:


#4

I see it now.

Thanks guys… it’s amazing how when you see the solution it makes immediately makes sense, but coming up with it in the first place makes the head spin.


#5

The Mozilla docs are your friend. I highly recommend taking the time, when you meet a new function or concept, that you take a look at the docs.

It’s a common gotcha – does a function update its calling object in place, or does it require a variable where the original data (which is left untouched) is copied and updated?