MPazik
MPazik

Reputation: 73

Are functions valid keys for javascript map collection?

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?

Upvotes: 2

Views: 383

Answers (1)

Pointy
Pointy

Reputation: 413866

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.

Upvotes: 9

Related Questions