Question

For a given hash:

var hash = {
    a: "one",
    b: { cat: "two" }
};

Using two pipes || allowing to place an alternative value if one doesn't defined:

var number = hash.a || "just a number";  // -> "one"
var number = hash.c || "just a number";  // -> "just a number"

However, targeting the nested hash will result an error: Cannot read property 'value' of undefined:

var number = hash.c.dog || "just a number";  // -> Cannot read property 'value' of undefined

My question is how to target a nested hash and set a default value as we're doing with a 'plain' hash?

Was it helpful?

Solution

JavaScript provides no special syntax for this. You need to test each potentially undefined value before assuming it's defined and trying to access one of its members.

You can still use || or && for this, but in a non-trivial case, it's probably better to just use an if.

Using ||:

var hash = {
    a: "one",
    b: { cat: "two" }
};

var x = (hash.c || {}).cat 

Using &&:

var x = hash && hash.c && hash.c.cat
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top