0
var foo = a.foo or {}
var bar = foo.bar or {}

It is tedious to do this for every level of nesting.

Can I somehow do instead?

var bar = a.foo.bar or {}
eugene
  • 39,839
  • 68
  • 255
  • 489
  • No, not really, since otherwise you would get property bar doesn't exist on undefined, you could however make a function that checks this – Icepickle Oct 14 '16 at 09:16
  • You could do it with a small utility function as well (though I also believe Nina's code to be the easiest), like such: https://jsfiddle.net/Icepickle/85cbq9h1/ – Icepickle Oct 14 '16 at 09:26

2 Answers2

2

You need a nested approach, you may have a look to logical operators and objects.

var bar = a && a.foo && a.foo.bar || {};
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

In javascript you need to use || to indicate for or.

var bar = a.foo.bar || {}; // However, a, a.foo may also be undefined

So, you need to check them using && operator to know if they all are defined:

var bar = a && a.foo && a.foo.bar || {};
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231