2

I would like to use functions as keys in JavaScript. I know that for js object, functions are converted to "toString" form. That is a problem if two functions have same body.

var a = function() {};
var b = function() {};
var obj={};
obj[a] = 1;
obj[b] = 2;

The value of obj[a] will contain 2.

If I use a Map it seems to be working fine.

var a = function() {};
var b = function() {};
var map = new Map();
map.set(a, 1);
map.set(b, 2);

The value of map.get(a) will return 1 and map.get(b), 2.

Is that a standard behaviour supported by all browsers or is this just a chrome browser implementation of Map collection? Can I relay on this? How functions are hashed in maps?

1 Answer 1

9

Object property names must be strings. If you try to use a value of any other type as a property key, the value is first converted to a string.

Now, a Map instance is a different story. Map keys can be of any type, according to the ES2015 spec (so it's something you can rely on in any environment supporting Map).

As to how a function value is "hashed", that's not defined in the spec. No two function instances will ever be the same, so even two different functions with the exact same body will serve as distinct Map keys.

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.