Generally, the logical or operator is used for this:
var theTitle = config.title || 'Untitled';
Basically, the right-hand operand is an expression that will -like all expressions- resolve to a definite value. It's processedd from left to right, so if config.title
is undefined, the string 'Untitled'
will be the resulting value.
You can chain logical operators if you need to, too:
var someVar = obj.val || anotherObject.val || yetAnother.foo || 'bar';
Or, if all operands are objects, and you don't know which one exists:
var foo = (bar || foobar || {property: 'default: none of the objects exist').property;
The object references are grouped together, so JS will first try to resolve the variables (left to right) to an existing value, or, in the end create a new object literal with the desired propert. That reference (the result of the grouped logical-ors) is accessed, and the property .property
is assigned to foo... I hope this is at least somewhat clear, if not: I'm sorry.
Caution
some properties might not be set at the instance level, or might be set, but assigned a falsy value. In that case, the logical OR is not enough, and you'll have to use either a ternary or a regular if...else
:
var foo = (obj.hasOwnProperty('val') ? obj.val : 'default');//<-- uses val property, even if it's undefined, as long as it's set on the instance
//or:
var foo = 'default';
if ('val' in obj)
{//val is set, either on the instance or on its prototype-chain
foo = obj.val
}
//as ternary:
var foo = ('val' in obj ? obj.val : 'default');