1

Does is matter whether I use | or || as an or operator? Both seem to work interchangeably.

function Sum(num, sum) {
    sum = sum | 0;
    return sum;
}

function SumII(num, sum) {
    sum = sum || 0;
    return sum;
}

console.log(Sum(7));
//0
console.log(SumII(7));
//0
Devon Luongo
  • 127
  • 2
  • 10
  • 4
    Possible duplicate of [Javascript conditional statement with a single pipe "|"](http://stackoverflow.com/questions/18594940/javascript-conditional-statement-with-a-single-pipe), also [What does this symbol mean in JavaScript?](http://stackoverflow.com/questions/9549780) or simply look at the JavaScript operator reference. – Sebastian Simon Dec 20 '15 at 00:57

3 Answers3

10

Yes, there is a huge difference.

The operator | is the bitwise operator or.
I cite the linked documentation:

Returns a one in each bit position for which the corresponding bits of either or both operands are ones.

So, by using this operator with two numbers will give you another number that is built from the first twos.

The operator || is the logical operator or.
It evaluates its operands as booleans (imagine as an implicit cast take place if needed) and it returns the first true value in its original form.

It happens that for certain operations the result is the same (as an example, if used in a guard, where the result of the applied operator is treated as a boolean value), no matter which operator you decide to use, but it would be better to know what are the differences between them.

skypjack
  • 45,296
  • 16
  • 80
  • 161
6

Logical operations

Use || and && instead of | and & because the first ones use a "short circuit" mechanism. So, they are more efficient (and safe) because if the left term was already evaluated to true / false, the result is known without evaluating the last terms.

E.g.: (for an undefined x)

true | x     // ReferenceError: x is not defined
true || x    // true
false & x    // ReferenceError: x is not defined
false && x   // false

Bits operations

Use | and &.

E.g.:

  • 4|2 returns 6

    4 = 100b
    2 = 010b
    6 = 110b
    (see the OR operation on every column: 1 OR 0 = 1, 0 OR 1 = 1, 0 OR 0 = 0)

  • 4||2 returns 4

    4 is a "true" value (because it is not 0,false,null,"", undefined or NaN) => the result doesn't depend on the bits values => the operator is not bitwise

Elrond_EGLDer
  • 47,430
  • 25
  • 189
  • 180
1

They are not the same

| is BITWISE OR operator. It takes the binary value of the two operands and compares each bit using OR logic.

|| is the LOGICAL OR operator. It checks the truthy-ness of each operand and compares those using OR logic.

Try for example

x = 42 || 65 // X now equals 42
x = 42 | 65 // X now equals 107 - 42 bitwise ORed to 65
tbernard
  • 467
  • 2
  • 12