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

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()?

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, @camperextraordinaire, but you got FAST fingers. I’ll bet you sniped ebay auctions, back in the day. :wink:

1 Like

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.

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?