html += '<td>'+(sd.someKey.s != "undefined") ? sd.someKey.s.a: '-'+'</td>'
I thought I'm doing the exception handling correctly but I'm getting error of Cannot read property 'a' of undefined
?
html += '<td>'+(sd.someKey.s != "undefined") ? sd.someKey.s.a: '-'+'</td>'
I thought I'm doing the exception handling correctly but I'm getting error of Cannot read property 'a' of undefined
?
You want to check sd.someKey.s !== undefined
. You can also check typeof sd.someKey.s !== "undefined"
. In most cases both will achieve the same result, but there are some edge cases where the latter is safer. I personally find the former more readable.
html += '<td>'+(sd.someKey.s !== undefined) ? sd.someKey.s.a: '-'+'</td>'
Also, it is typically better to use the !==
notation instead of !=
.
Which equals operator (== vs ===) should be used in JavaScript comparisons?
Try using Object.hasOwnProperty()
html += "<td>"
+ (sd.someKey.hasOwnProperty(s)
&& sd.someKey.s.hasOwnProperty(a)
? sd.someKey.s.a
: "-"
+ "</td>"
As @DelightedD0D mentioned in one of his comments, You should use typeof
to find out if object is undefined.
I've made some fiddle link for you-
https://jsfiddle.net/2oud68gL/
html = (typeof(sd.someKey.s) != 'undefined') ?sd.someKey.s.a: '-';