Appendix B. Frequently Misunderstood JavaScript Concepts

This book is not designed to teach you JavaScript, but it does recognize that you are likely to have taught yourself JavaScript and that there are some key concepts that you may have missed along the way. This section is particularly important if your primary language is Java, as the syntactic similarities between Java and JavaScript belie the differences in their respective designs.

JavaScript Objects Are Associative Arrays Whose Keys Are Always Strings

Every object in JavaScript is an associative array whose keys are strings. This is an important difference from other programming languages, such as Java, where a type such as java.util.Map is an associative array whose keys can be of any type. When an object other than a string is used as a key in JavaScript, no error occurs: JavaScript silently converts it to a string and uses that value as the key instead. This can have surprising results:

var foo = new Object();
var bar = new Object();
var map = new Object();

map[foo] = "foo";
map[bar] = "bar";

// Alerts "bar", not "foo".
alert(map[foo]);

In the previous example, map does not map foo to "foo" and bar to "bar". When foo and bar are used as keys for map, they are converted into strings using their respective toString() methods. This results in mapping the toString() of foo to "foo" and the toString() of bar to "bar". Because both foo.toString() and bar.toString() are "[object Object]", the previous code is equivalent to:

var ...

Get Closure: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.