Sam Merrell:
> What are the groups thoughts on safely accessing a nested objects
> value that may be undefined?
Firstly you should answer on the question, are you going to create
objects which properties value 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 looks broken by design. Usually you are not going to create such
a code. You must NOT existence of properties during accessing stage.
First of all you should define the semantic of `persons`. The user of
code must follow this semantic and you would not need to check
properties, especially in this way.
Another approach is to create constructor `Person' who will be
responsible for these things. In constructor your are going to deal
with the default values and etc.
And when you access e.g `zip` property you must write:
personN.address.zip;
Now you are get the default value of `zip` or user defined.
If this object is not created by your constructor and does not follow
the semantic of `person` you will get valuable TypeError, which will
help you to consider the problem.
At all you shouldn't create magic code and should think about for easy
debugging.
--
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]