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 {}
2
  • No, not really, since otherwise you would get property bar doesn't exist on undefined, you could however make a function that checks this Commented Oct 14, 2016 at 9: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: jsfiddle.net/Icepickle/85cbq9h1 Commented Oct 14, 2016 at 9:26

2 Answers 2

2

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

var bar = a && a.foo && a.foo.bar || {};
Sign up to request clarification or add additional context in comments.

2 Comments

Won't this return false if a or a.foo is undefined.
Oh, javascript && operator does return full object, not the truth value. Thanks.
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 || {};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.