Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  34] [ 5]  / answers: 1 / hits: 15803  / 13 Years ago, fri, july 1, 2011, 12:00:00

It seems that the following technique for checking the existence of an object member produces an error because the 'bar' parent object hasn't been declared before the check, which means I either have to declare it before the check or use two 'typeof' expressions, either of which would be excess code:



var foo = {},
newVal = (typeof foo.bar.myVal !== 'undefined' ? foo.bar.myVal : null );

Error: foo.bar is undefined


So, how do you check if a member within an undeclared object exists without producing an error?



I love javascript, but sometimes...


More From » object

 Answers
16

It can be done simply using the code below:



var newVal = (foo && foo.bar && typeof foo.bar.myVal !== 'undefined') ? foo.bar.myVal : foo.bar.myVal


A property is null or undefined, it will be evaluated as false so the above code will only process up to the first 'false' statement.


[#91402] Thursday, June 30, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
braeden

Total Points: 231
Total Questions: 96
Total Answers: 86

Location: Somalia
Member since Mon, Dec 28, 2020
3 Years ago
;