Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Generally, the logical or operator is used for this:</p> <pre><code>var theTitle = config.title || 'Untitled'; </code></pre> <p>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 <code>config.title</code> is undefined, the string <code>'Untitled'</code> will be the resulting value. <br/> You can <em>chain</em> logical operators if you need to, too:</p> <pre><code>var someVar = obj.val || anotherObject.val || yetAnother.foo || 'bar'; </code></pre> <p>Or, if all operands are objects, and you don't know which one exists:</p> <pre><code>var foo = (bar || foobar || {property: 'default: none of the objects exist').property; </code></pre> <p>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 <code>.property</code> is assigned to foo... I hope this is at least somewhat clear, if not: I'm sorry.</p> <p><em>Caution</em><br/> 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 <code>if...else</code>:</p> <pre><code>var foo = (obj.hasOwnProperty('val') ? obj.val : 'default');//&lt;-- 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'); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload