On Tue, Feb 15, 2011 at 12:02 AM, 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]
>
I believe this is almost equivalent:
try { a = person2.address.zip; } catch(err) { a = 'no zip'; }
and if needed frequently build an "hasPath()" function around it as
suggested by Peter.
--
Diego
--
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]