-1
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 ?

gagan mahatma
  • 336
  • 2
  • 9
Jennifer
  • 905
  • 9
  • 20

3 Answers3

0

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?

Community
  • 1
  • 1
ken4z
  • 1,340
  • 1
  • 11
  • 18
  • I dont think this is correct, please see [Detecting an undefined object property](http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property) which states to use `if (typeof something === "undefined")` – Wesley Smith Jan 08 '16 at 03:03
  • Both will achieve the correct result http://www.2ality.com/2013/04/check-undefined.html – ken4z Jan 08 '16 at 03:07
  • Fair point, however do note that undefined is not a reserved word. It is is a property of the global object, i.e. it is a variable in global scope. It can be used as an identifier (variable name) in any scope other than the global scope. oR in other words, it can be overwritten to contain any value (though it is not advisable to do so). Additionally, it is more advisable to use `typeof` because it does not throw an error if the variable has not been declared. Taken from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined – Wesley Smith Jan 08 '16 at 03:14
0

Try using Object.hasOwnProperty()

html += "<td>" 
        + (sd.someKey.hasOwnProperty(s)  
          && sd.someKey.s.hasOwnProperty(a) 
          ?  sd.someKey.s.a 
          : "-" 
          + "</td>"
guest271314
  • 1
  • 15
  • 104
  • 177
0

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: '-';
Manoz
  • 6,507
  • 13
  • 68
  • 114