0

I m new to JavaScript and facing a weird problem. after adding months to asset_purchase_date into a new variable, the value of asset_purchase_date is changing automatically.

function AssetValueToday(asset_purchase_date, asset_total_cost, asset_life_months, asset_sale_date, asset_value_ason) {
  var return_value = 0;

  if (asset_sale_date > asset_value_ason) {
    if (asset_value_ason > asset_purchase_date) {
      days_since_purchase = (Math.ceil(Math.abs(asset_value_ason - asset_purchase_date)) / (1000 * 60 * 60 * 24));
      asset_end_date = addMonths(asset_purchase_date, asset_life_months);

      // here do some stuff

    }
    return_value = asset_purchase_date;
  } else {
    return_value = 0;
  }
  return return_value;
}

function addMonths(date, months) {
  date.setMonth(date.getMonth() + months);

  return date;
}

Any help shall be highly appreciated.

Nexo
  • 2,125
  • 2
  • 10
  • 20
Amer Hamid
  • 145
  • 6
  • hi, are there any other references to `asset_purchase_date` that might modify it – jspcal Jan 17 '23 at 18:16
  • @jspcal No. i have pasted the whole code. btw, I am using this in Google sheets. – Amer Hamid Jan 17 '23 at 18:17
  • @AmerHamid: What specifically do you mean by "getting changed automatically"? When you step through the code with a debugger, which specific operation first produces an unexpected result? What were the values used in that operation? What was the result? What result were you expecting? Why? – David Jan 17 '23 at 18:19
  • @David after calculating asset_end_date, the same value of asset_end_date is getting assigned to asset_purchase_date – Amer Hamid Jan 17 '23 at 18:22

1 Answers1

1

This is because setMonth modifys the Date object (asset_purchase_date). See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth

You have to create a new Date object, something like:

function addMonths(date, months) {
  const newDate = new Date(date.getTime())
  newDate.setMonth(newDate.getMonth() + months);
  return newDate;
}
Thierry
  • 5,133
  • 3
  • 25
  • 30
  • 1
    It is worth mentioning that an object passed to a JS function gets modified only if the function makes changes *to its fields* (or calls its functions). If it changes the object *in whole*, the change is local (inside function). – SNBS Jan 17 '23 at 19:15