23

What's the difference between | and || in Javascript?

Furthermore, what's the difference between & and &&?

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
Buffon
  • 373
  • 2
  • 4
  • 9
  • 4
    It should be noted that this is not javascript specific. Almost every programming language uses the same operators for the same functions. – Brian Roach Apr 17 '11 at 00:13
  • 1
    @Brian Roach : Sorry for that!! – Buffon Apr 17 '11 at 00:19
  • no need, I was just mentioning it. – Brian Roach Apr 17 '11 at 00:21
  • @BrianRoach - Actually JavaScript's `||` and `&&` _are_ different to (many) other programming languages because they return the value of one or other operand and _not_ a boolean (unless the operands are themselves booleans, of course). – nnnnnn Feb 16 '12 at 06:52
  • @nnnnnn - they're not in how they *differ* from `|` and `&`. The double are logical operations, the single bitwise operations. The return value of the logicals in JS wasn't part of the question. Furthermore, when used in an `if` statement the value is only false if it is `== 0`. All other conditions are treated as 'true'. The fact that it's returning the value is simply a side effect and is discarded. In `Java` for example, the logical `&&` and `||` operators *only* take boolean arguments; this doesn't affect the fact that `&&` and `||` are logical and `&` and `|` are bitwise operators. – Brian Roach Feb 16 '12 at 07:21
  • @BrianRoach - Sure, in a general sense bitwise versus non-bitwise is the main point. And if used in an `if` statement a return of `true` versus a return of a truthy value makes no difference. But the question doesn't mention `if` statements, nor does it say anything about the types of the operands. So given that this question was flagged as "JavaScript" the way the logical operators work _does_ matter and the type of the operator's return is important too. – nnnnnn Feb 16 '12 at 08:05

7 Answers7

25

| is a bitwise or, || is a logical or.

A bitwise or takes the two numbers and compares them on a bit-by-bit basis, producing a new integer which combines the 1 bits from both inputs. So 0101 | 1010 would produce 1111.

A logical or || checks for the "truthiness" of a value (depends on the type, for integers 0 is false and non-zero is true). It evaluates the statement left to right, and returns the first value which is truthy. So 0101 || 1010 would return 0101 which is truthy, therefore the whole statement is said to be true.

The same type of logic applies for & vs &&. 0101 & 1010 = 0000. However 0101 && 1010 evaluates to 1010 (&& returns the last truthy value so long as both operands are truthy).

Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
  • 5
    Then question marks indeed. Don't use the bitwise `or` operator unless it's for bitwise things. – Chris Eberle Apr 17 '11 at 00:22
  • @Buffon then there converted to a number and your basically calling `NaN & NaN` which is 0. – Raynos Apr 17 '11 at 00:26
  • 3
    _"However a logical or `||` simply checks the truth value of both inputs. So `0101 || 1010` would produce true"_ - This is wrong on two counts. Firstly, `||` uses short-circuit evaluation, so if the first operand is "truthy" the second operand is not evaluated at all. Secondly, `||` doesn't return `true` or `false`, it returns the value of the first operand if truthy, otherwise the value of the second operand. So `0101 || 1010` returns `0101` (or 65 given that a leading 0 in a numeric literal makes it octal). `'A' || 'B'` returns `'A'`. – nnnnnn Feb 16 '12 at 06:47
  • @nnnnnn very interesting. I knew about the short circuiting, but I didn't realize it returned the first truthy value. How does `&&` treat truthy values then (since it's not short-circuited)? – Chris Eberle Feb 16 '12 at 16:37
  • && uses short-circuit evaluation too: if the first operand is "falsy" then it is returned and the second operand is not evaluated, otherwise the second operand is returned. – nnnnnn Feb 16 '12 at 19:55
  • @nnnnnn ah yes, I was thinking short circuiting for the false case. Good to know, I'll update this appropriately. Thanks. – Chris Eberle Feb 16 '12 at 21:01
  • @SiPlus did you read the comment history, or just jump in? You are incorrect. – Chris Eberle Feb 10 '13 at 23:19
13

The difference is that logical operators only consider each input at face value, treating them as whole, while bitwise operators work at the bit level:

var thetruth = false;
var therest = true;

var theuniverse = thetruth && therest; //false
var theparallel = thetruth && thetruth; //true

var theindifferent = thetruth || therest; //true
var theideal = thetruth || thetruth; // false

var thematrix = 5346908590;
var mrsmith = 2354656767;

var theoracle = thematrix & mrsmith; //202445230
var theone = thematrix | mrsmith; //7499120127
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
4

Another difference is that || uses shortcut evaluation. That is, it only evaluates the right side if the left side is false (or gets converted to false in a boolean context, e.g. 0, "", null, etc.). Similarly, && only evaluates the right side if the left side is true (or non-zero, non-empty string, an object, etc.). | and & always evaluate both sides because the result depends on the exact bits in each value.

The reasoning is that for ||, if either side is true, the whole expression is true, so there's no need to evaluate any further. && is the same but reversed.

The exact logic for || is that if the left hand side is "truthy", return that value (note that it is not converted to a boolean), otherwise, evaluate and return the right hand side. For &&, if the left hand side is "falsey", return it, otherwise evaluate and return the right hand side.

Here are some examples:

false && console.log("Nothing happens here");
true || console.log("Or here");
false || console.log("This DOES get logged");
"foo" && console.log("So does this");

if (obj && obj.property) // make sure obj is not null before accessing a property
Matthew Crumley
  • 101,441
  • 24
  • 103
  • 129
  • +1. This is the only correct explanation (so far) of `||`. Nobody else mentioned short-circuit evaluation, and nobody else mentioned that the operator returns the actual value of the first or second operand, _not_ a boolean. – nnnnnn Feb 16 '12 at 06:50
1

In Javascript perspective, there is more to it.

var a = 42;
var b = "abc";
var c = null;

a || b;     // 42
a && b;     // "abc"

c || b;     // "abc"
c && b;     // null

Both || and && operators perform a boolean test on the first operand (a or c). If the operand is not already boolean (as it's not, here), a normal ToBoolean coercion occurs, so that the test can be performed.

For the || operator, if the test is true, the || expression results in the value of the first operand (a or c). If the test is false, the || expression results in the value of the second operand (b).

Inversely, for the && operator, if the test is true, the && expression results in the value of the second operand (b). If the test is false, the && expression results in the value of the first operand (a or c).

The result of a || or && expression is always the underlying value of one of the operands, not the (possibly coerced) result of the test. In c && b, c is null, and thus falsy. But the && expression itself results in null (the value in c), not in the coerced false used in the test.

user3278612
  • 201
  • 2
  • 11
1

Single | is bit wise OR operator . If you do 2 | 3 , it converts to binary and performs OR operation. 01 11 Results in 11 equal to 3.

Where as || operator checks if first argument is true, if it is true it returns else it goes to other operator. 2 || 3 returns 2 since 2 is true.

sridhar..
  • 1,945
  • 15
  • 19
1

To explain a little more in layman's terms:

&& and || are logical operators. This means they're used for logical comparison;

if (a == 4 && b == 5)

This means "If a equals to four AND b equals to five"

| and & are bitwise operators. They operate on bits in a specific fashion which the wiki article explains in detail:

http://en.wikipedia.org/wiki/Bitwise_operation

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
0

one more point i want to add is || operator is used to assign default value in case the value you are assigning is undefined. So for Exapmle you are assigning a obj to some object test and if you dont want test to be undefined then you can do the following to ensure that value of test wont be undefined.

var test = obj || {};

so in case obj is undefined then test's value will be empty object.

So it is also being used for assigning default value to your object.

Fire-Hox
  • 523
  • 4
  • 5
  • I think you mean undefined or null by saying "so in case obj is undefined then test's value will be empty object.". – thread-game Apr 15 '17 at 16:23