Thanks for the suggestions! I kept looking at the code and it does feel like its harder to understand than just using an if like Angus pointed out. It definitely feels like I'm trying to be a little too clever in getting to the zip property.
I think my main reasoning for checking the zip the way I was is that this data is coming from local storage and may or may not be there at all or have only incomplete data (e.g. the person may have a zip but no county or no address at all). I should really take a look at how I'm storing the data and try to keep nesting down as much as possible so that my checks become more simple. On Tue, Feb 15, 2011 at 08:37, Michael Haufe (TNO) <[email protected]> wrote: > Looks like a code smell of bad design. If you have a Person object it > would be unnecessary to do member sniffing tests and literal > injections like this. > > So instead of this: > > var person = {address: {zip: 1234}}, > person2 = {}; > console.log("Person2 undefined: " + > ((person2||{}).address||{}).zip || "no zip"); > > I'd say do this: > > var person = new Person(new Address(1234)), > person2 = new Person(); > console.log(person2.zip || "no zip"); > > On Feb 14, 5:02 pm, Sam Merrell <[email protected]> wrote: >> Hi all >> , >> What are the groups thoughts on safely accessing a nested objects >> value that may be undefined? I recently came across a blog post [1] >> from Oliver Steele where he did a shortcut that looks like this: >> >> var person = {address: {zip: 1234}}, >> person2 = {}; >> console.log("Person2 undefined: " + >> ((person2||{}).address||{}).zip || "no zip"); >> >> This takes the place of code like this: >> >> if(person2 && person2.address) >> console.log("Person2 zip: " + person2.address.zip); >> >> 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? >> >> [1]http://osteele.com/archives/2007/12/cheap-monads > > -- > 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] > -- 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]
