On Feb 14, 5:02 pm, Sam Merrell <[email protected]> wrote: > What are the groups thoughts on safely accessing a nested objects > value that may be undefined? > [snip] > Does the code lose readability when done with that sort of shorthand? > Also, is there the possibility of a performance hit for creating > multiple empty objects?
I'm apparently in the minority but i really like the "or empty object" idiom when dereferencing optional properties. Keep in mind that you don't need to create new empty objects each time. You could use a constant (like true or false) or zero, or something like that: ((person || 0).address || 0).zip || 'no zip'; or ((person || false).address || false).zip || 'no zip'; I have no idea if there would be a performance benefit to that or not since the JS engine will probably convert it to the wrapper object (Number/Boolean) when you try to access properties on it. It'd be nice if we had CoffeeScript's safe dereferencing (http:// jashkenas.github.com/coffee-script/#operators): person?.address?.zip or 'no zip' - Ben -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/[email protected]/ To search via a non-Google archive, visit here: http://www.mail-archive.com/[email protected]/ To unsubscribe from this group, send email to [email protected]
