0

I basically want to do var a = b.c.d || null

but the issue is, a might be undefined, b might be, or c might be

so short of ugly try{} catch{} or if statements what is the best way to do this? this is for constructing a quite large object (say 50 odd properties) from a 3rd party data source

putvande
  • 15,068
  • 3
  • 34
  • 50
DrogoNevets
  • 1,456
  • 3
  • 18
  • 34
  • ES2015: `let { c: { d: a = null } = {} } = b;` – zerkms Jun 03 '15 at 08:27
  • That's why it's not an answer but a comment :-) – zerkms Jun 03 '15 at 08:29
  • This has been asked a couple of times already: [`[javascript] nested property exists`](http://stackoverflow.com/search?q=%5Bjavascript%5D+nested+property+exists). Does really none of those solve your issue? Why not? – Felix Kling Jun 03 '15 at 08:29

3 Answers3

2
var a = ( b && b.c && ('d' in b.c)) ? b.c.d : null;
zerkms
  • 249,484
  • 69
  • 436
  • 539
dopeddude
  • 4,943
  • 3
  • 33
  • 41
1
var a;
if(b !== undefined && b.c !== undefined && b.c.d !== undefined){
   a = b.c.d;
} else {
 a = null;
}

Shorthand

var a = b !== undefined && b.c !== undefined && b.c.d !== undefined ? b.c.d : null

Every condition will exit immediatly the statement if undefined as long as the logical operator is && This will work for undefined value of b b.c and b.c.d

I am wondering that you may try with a boolean casting, something like

var a = !!b && !!(b.c) && !!(b.c.d) ? b.c.d : null

This will fail for value 0 of b.c.d

steo
  • 4,586
  • 2
  • 33
  • 64
-1

In my opinion try catch in this case is not ugly: with a try I am asking the code to see if b.c.d exists and a ReferenceError in this case is some kind of "expected behaviour". Remember that an Exception is not necessary an error. There are many frameworks like TurboGears that uses Exception to change the program flow rapidly and not necessary when raising an Error.

pinturic
  • 2,253
  • 1
  • 17
  • 34