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

0
2
Asked By MellowPine47 On

I'm trying to understand pointers and object references in JavaScript. My original goal was to make an entry associated with a key refer to the exact same object as a value, so that checking map.get(key) === value would return true. I tried Object.assign(map.get(key), value), and while map.get(key).start === value.start is true, map.get(key) === value is false. What is the correct way to do this?

2 Answers

Answered By SunnyOrbit26 On

The basic operation is simply key = value when you want two variables to reference the same object. For a Map, use map.set(key, value). Object.assign(target, source) expects the first argument to be the object being modified and copies properties from the second argument; it is not a pointer-assignment operation.

MellowPine47 -

That explains the behavior I was seeing. The matching start properties only showed that the objects had copied data, not that they were the same object. Using map.set(key, value) gives me the identity check I wanted.

Answered By CobaltRaven8 On

Object.assign() does not make two objects identical or connect their references. It copies enumerable properties from the source object into the target object, so map.get(key) and value remain separate objects even if they contain the same data. If you want the map entry to refer to the exact same object, assign the value directly: map.set(key, value). Then map.get(key) === value will be true.

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.