There's a risk using objects as associative arrays in JavaScript. Consider:
var foo = {};
function putFoo(x, v) {
foo[x] = v;
}
function getFoo(x) {
return foo[x];
}
putFoo("a", "blah");
console.log("a", getFoo("a")); // Yes, "a" is there.
console.log("b", getFoo("b")); // No, "b" is not there.
console.log("toString", getFoo("toString")); // what?
Everything is swell until you get to the last console.log
. toString
is a method in Object.prototype
from which object literals get their methods, so you'll get a function out on the console even though you never put anything named toString
in the object.
You can work around this by creating your object with Object.create(null)
. This will create an object that does not have a prototype, and so is not polluted by the members of Object
. (Documentation on Object.create.)
Here's a question that explores the performance issues. In brief creating an object with Object.create(null)
is more expensive than with {}
but accessing the keys on an object created by Object.create(null)
is faster than on an object created with {}
.