0

Something weird is happening with Javascript as I try to copy an object, and set one of the copied variables to 1. When I console.log the variable directly, it's set. When I console.log the object, that value is undefined.

    const addedItem: ProductToPlan = (JSON.parse(JSON.stringify(item)));
    addedItem.amountToAdd = 1;
    console.log(addedItem.amountToAdd);
    console.log(addedItem);

The object ProductToPlan does have the variable 'amountToAdd' defined in its class definition (as a number).

Screenshot of the console: Console log As you can see, te first line echoes '1' as it should, but then when I echo the object, it's undefined.

It's quite possible I'm doing something wrong, I just don't know what it is or what to search for.

What am I missing?

Martijn Brouwer
  • 749
  • 3
  • 8
  • 2
    Is there anything that process `addedItem` afterwards - some validation checks, perhaps? It seems that the object is adjusted by other piece of code when you look at it. You can try to log the stringified value of this object instead just to make sure. – raina77ow Jun 22 '21 at 07:38
  • I had a look, it just makes things even weirder. Yes, there's a function that changes these values afterwards. I've disabled those. (I can't insert a screenshot in a comment), but the object says amountToAdd is 1, but when I expand the object, it's undefined again. So weird, but it gives me a place to search. Thanks! – Martijn Brouwer Jun 22 '21 at 07:51
  • 1
    [Weird behavior with objects & console.log](https://stackoverflow.com/q/23429203) - when printing a live reference to an object, it will be evaluated *when you expand it*. This can lead to the behaviour you observe - at log time it says the value is one thing but when you expand it it's another. – VLAZ Jun 22 '21 at 08:14
  • @VLAZ This seems to be indeed what's happening. Thank you for keeping my sanity intact! – Martijn Brouwer Jun 22 '21 at 08:30
  • 1
    Unfortunately, I have bad news for your sanity if you're doing software development. I used to be sane but nowadays I can tell you about weird problems like this one, or how some old version of some product malfunctioned in some very specific circumstances, and similar all more easily than recalling what I had for breakfast. [Programming sucks.](https://www.stilldrinking.org/programming-sucks) – VLAZ Jun 22 '21 at 08:56

0 Answers0