How can I make two JavaScript references point to the same object?

0
10
Asked By MellowCedar42 On

I'm trying to understand whether JavaScript supports pointer-like behavior. My original problem is that I'm using `Object.assign(map.get(key), value)`, and although `map.get(key).start === value.start` returns `true`, `map.get(key) === value` returns `false`. How can I make the object stored for `key` be the exact same object as `value`?

2 Answers

Answered By QuietOrchid18 On

In JavaScript, variables and map values hold references to objects, but object identity is separate from having equal properties. `Object.assign(existing, value)` leaves `existing` and `value` as two different objects with copied properties. Use `const sameObject = value`, or replace the entry with `map.set(key, value)` when working with a `Map`.

Answered By BrightLynx7 On

`Object.assign()` copies properties from a source object onto a target object; it does not make the target and source the same object. If you want the map entry to reference `value` directly, assign it with `map.set(key, value)`. Then `map.get(key) === value` will be `true`.

MellowCedar42 -

That makes sense. I was mutating the existing object returned by `map.get(key)`, rather than replacing the map entry with `value` itself.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.