0

I have the following snippet of code buried deep within a complicated function:

                 result = {
                    ...result,
                    mp_mods: {
                        ...result.mp_mods,
                        Untyped: {
                            ...result.mp_mods.Untyped,
                            [kitObj.id]: {
                                num: 2,
                                level
                            }
                        }
                    }
                };
                let newVar = {
                    ...result,
                    mp_mods: {
                        ...result.mp_mods,
                        Untyped: {
                            ...result.mp_mods.Untyped,
                            [kitObj.id]: {
                                num: 2,
                                level
                            }
                        }
                    }
                };
                console.log(result.mp_mods);
                console.log(newVar.mp_mods);

These two console.logs are producing different results. newVar looks like I want it to, while result still looks the same as it did before I tried to assign a new value to it. It seems to be (undesirably) immutable, due to ... some complicated rule of scope or something?

result was originally declared with let, not const, so that's not the reason. (Too bad, that would have generated a clear error message and been easy to fix.)

Can anyone explain what is going on here? There must be something in my code preceding this snippet that's problematic. But I need to modify result, and I currently can't!

McKayB
  • 13
  • 4
  • can you post complete code, or create an example to reproduce this, currently with the given code i don't see any reason for this behaviour – Code Maniac May 02 '20 at 03:39
  • I bet you're changing `result` later on. Is there a little blue _"i"_ next to any of the console messages? If so, that means they've changed since logging. `console.log` is a terrible debugging tool as it updates object references live. Use your browser's debugger instead. See [How can I make console.log show the current state of an object?](https://stackoverflow.com/questions/7389069/how-can-i-make-console-log-show-the-current-state-of-an-object) – Phil May 02 '20 at 03:39
  • as a quick solution: Did you try to create newVar and assign it to result later? It could solve your problem in the meantime... – Roberto C. Rodriguez-Hidalgo May 02 '20 at 03:43

0 Answers0