Practical prototype and part 10: The information in this book is distributed on an "as is" basis, without warranty Although every pre-caution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. | 42 CHAPTER 3 COLLECTIONS OR NEVER WRITE A FOR LOOP AGAIN var obj - Object obj name Statue of Liberty constructor Frédéric Bartholdi - Frédéric Bartholdi In this example a built-in property constructor that has special meaning in JavaScript is being shadowed by a property of the same name that we assign on the object instance. Similar collisions can occur with toString valueOf and other built-in properties. The safety of any arbitrary key cannot be guaranteed. These might seem like edge cases but key safety is especially important when you re building a hash in which the key names depend on user input or on some other means that isn t planned beforehand by the developer. The Problem As we briefly covered in Chapter 2 JavaScript suffers from a flaw caused by two of its features stepping on one another. In theory we can define properties on and have them propagate to every instance of Object. Unfortunately when properties are enumerated in a loop anything that s been defined on will get picked up. function iterator for var i in this iterator i this i var obj name Statue of Liberty constructor Frédéric Bartholdi pass the key and value as arguments to name Statue of Liberty constructor Frédéric Bartholdi each function iterator for var i in this iterator i this i CHAPTER 3 COLLECTIONS OR NEVER WRITE A FOR LOOP AGAIN 43 Regrettably there s no way to suppress this behavior. We could get around it by avoiding ordinary loops altogether wrapping code around them that ensures we enumerate only properties that exist on the instance but then we ve only solved the problem for our own scripts. Web pages often pull in scripts from various sources some of which may be unaware of each other s existence. We can t expect all these scripts to boil the ocean just to make our lives a little easier. The Solution There s a way around all .