I’m a fan of using short circuit evaluation for these kinds of situations:
items && items[val] && doSomething(items[val])
Some people might be repulsed by this, but I think it’s a nice and readable way to express something that should only be evaluated if certain conditions are met.
In this case, we’re actually chaining two short circuit evaluations. First, we determine whether items
has a defined value. If it undefined, then the rest of the expression is moot, so we won’t even bother to evaluate it. AND if it is defined, then let’s check for the existence of some property that we’re interested in. If it’s undefined, then bail out. AND if it’s true, we can go ahead and evaluate the rest of the expression.
I think it’s a lot easier to reason through at a glance than:
if (items) {
if (items[val]) {
doSomething(items[val])
}
}
Ternary operators work similarly:
items
? items[val]
? doSomething(items[val])
: alert(‘The property “‘ + val + ‘“ has not yet been defined.’)
: alert(‘You have not yet defined any items!’)