3

I've been trying to get a hold of ES2015 map concept and one thing I don't understand is the following:

var mapRawObj = new Map();
var rawObj = {j:"I like penguin"};
mapRawObj.set(rawObj,true);
console.log(mapRawObj.get(rawObj)); //this outputs true

mapRawObj.set({j:"I like polar bear"},true);
console.log(mapRawObj.get({j:"I like polar bear"})); //this outputs undefined

The first one works, the second one doesn't, and I don't understand why?

I thought when you register object as key, it's the object itself, not the object's name. That's why in the below example when you re-assign the key object, it fails as key?

var obj = { a:"hello ", b:"world "};
var mapObj = new Map();
mapObj.set(obj,true);
obj = {d:34}; //obj is re-assigned
console.log(mapObj.get(obj)); // outputs undefined
1
  • In your second example you basically have the same situation as in your second code snippet. So either you understand both or none of them. I'm confused. Commented May 12, 2016 at 13:09

1 Answer 1

7

Objects with the same data are not equal in Javascript, ie

{ hello: 'world'} === { hello: 'world'} // false

The first example uses the same object as the key for set and get, so the key is identical:

var obj = { hello: 'world'};
obj === obj // true

But the second example creates a new object for the get(), which is not identical to the key used to set the value in the map. Since it's not identical, the map doesn't have anything set against this new key and returns undefined.

Even though the new key has exactly the same data as the original key, the objects aren't referring to the same data internally.

More on object equality

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.