Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of || in javascript?

Tags:

javascript

I am looking at these lines of code from here:

    if (callback)
        callback(sig || graph);

I have never see vertical "or" bars in a javascript method call. What do they mean? Do they pass the "true" parameter (i.e. sig or graph)? Do they pass the defined parameter? I have never seen that syntax before.

like image 445
bernie2436 Avatar asked May 07 '15 17:05

bernie2436


People also ask

What does && and || mean in JavaScript?

If applied to boolean values, the && operator only returns true when both of its operands are true (and false in all other cases), while the || operator only returns false when both of its operands are false (and true in all other cases).

What is || used for?

We use the symbol || to denote the OR operator. This operator will only return false when both conditions are false. This means that if both conditions are true, we would get true returned, and if one of both conditions is true, we would also get a value of true returned to us.

What does || do in JavaScript for strings?

The || operator, for example, will return the value to its left when that can be converted to true and will return the value on its right otherwise.

What does || in coding mean?

Logical OR operator: || The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.


2 Answers

This is the logical OR operator in JS (and most other languages). It is defined in the spec at 11.11. As noted in the spec, expressions on either side will be evaluated first and the logical OR is left-to-right associative. Note that evaluation of the operands follows standard ToBoolean semantics from section 9.2, so [null, undefined, 0, ''] all count as falsy.

Unlike most languages, JS returns the left operand if it is truthy or the right operand otherwise. This behavior has been covered before in a number of SO questions, but is worth noting as most languages simply return true or false. This behavior is often used to provide default values to otherwise undefined variables.

like image 89
ssube Avatar answered Oct 05 '22 15:10

ssube


The Logical OR operator (||) is an operator that returns its first or second operand depending on whether the first is truthy. A "truthy" value means anything other than 0, undefined, null, "", or false.

This operator uses short-circuiting, meaning if the first expression is truthy, then the second expression is not evaluated and the first operand is returned immediately. This is akin to the Logical AND operator (&&), which does the opposite: if the first operand is falsey, it returns it, otherwise it returns the second expression.

like image 26
David G Avatar answered Oct 05 '22 17:10

David G