This question already has answers here:
Javascript conditional statement with a single pipe "|"
(4 answers)
Closed 7 years ago.
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
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.
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
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
Related
Just wondering if anyone has come across this before.
I found in a project (that was handed over from another developer) a conditional statement that looked something like this:
if (variableOne == true | variable2 == true) {
// Do something here
}
It didn't error, so seems to work. But, myself and a colleague have never seen an OR statement with a single pipe |, only 2 ||.
Can anyone shed light on this mystery?
Thanks,
James
This is a bitwise OR operator. It will first convert it into a 32 bit integer, then apply the bitwise OR operation to the two numbers that result. In this instance, since Boolean(1) is true and Number(true) is 1, it will work fine without issue (the == operator will always return a boolean, and a if statement converts anything to a boolean). Here are a few examples of how it works:
1 | 0; // 1
0 | 0; // 0
0 | 1; // 1
1 | 1; // 1
true | false; // 1
false | false; // 0
2 | 1; // 3 (00000010, 00000001) -> (00000011)
As both sides have to be converted to a number (and therefore evaluated), this may cause unexpected results when using numbers when the logical OR statement (||) was meant to be used. For this, take these examples:
var a = 1;
a | (a = 0);
console.log(a); // 0
var b = 1;
b || (b = 0);
console.log(b); // 1
// I wanted the first one
var c = 3 | 4; // oops, 7!
Reference: http://www.ecma-international.org/ecma-262/5.1/#sec-11.10
That's a bitwise OR, see the documentation from Mozilla: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators)
The two pipes syntax "||" means it short circuits the logical expression. Evaluating only the needed until it knows the result.
What does it means?
if(a==null || a.type=='ok')
If a is null, it will evaluate only the first part of the expression, without errors on javascript side.
if(a==null | a.type=='ok')
If a is null in this case, you will have an error, since it will evaluate the second part of the expression too.
It's the same thing on others C type languages: Java, C,C++
And the same thing applies to '&' and '&&'
| is a bitwise OR, which in some very limited cases can substitute the ||.
An important difference is that with | both operands are evaluated, unlike with the || which evaluates the second operand only if the first is false.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
This question already has answers here:
What's the difference between & and && in JavaScript?
(4 answers)
Closed 3 years ago.
I have two conditions that validate if "a" equals zero and "b" less than 5, both behave in the same way, but with different operators, is there any real difference between them?
var a = 0;
var b = 3;
if (!a & (b < 5)) {
}
if (!a && b < 5) {
}
The key difference is that the & operator is a bitwise operator, while the && operator is a logical operator.
Bitwise operators work on bits and perform "bit by bit" operations, they are applied to the bits of one or two operands. The & represents a bitwise AND operation- where A and B represent two inputs; both inputs must be true in order for C to be true.
So for instance in the example you provided you have:
if(0 & 1){
}
The result of the bitwise AND on 0 and 1 as inputs is 0 (false) because both inputs must be true for the output to be true.
The && operator is a logical operator, which is used to make a decision based on multiple conditions. It can apply to one or two operands each of which may be true or false.
if (!a && b < 5) {
}
The above still evaluates to false because both conditions must be met for the code inside the if statement to be executed. In addition to this, using the && operator will (depending on the language) short circuit, which means that the second condition of the if will only be evaluated if the outcome is not determined by the first condition.
So this expression will fail as soon as a is found to be zero (false) because there is no point in evaluating the second expression as the first expression had to be true. This is another difference as the bitwise & operator does not short circuit.
This question already has answers here:
JavaScript OR (||) variable assignment explanation
(12 answers)
Closed 6 years ago.
I am not getting what or operator does with inters. I have following code
-1||4 // output -1
4||-1 //output 4
Does it converts integers in bytes and performs or operation.
It first checks wheter the number is truthy or falsey and returns the first truthy one. All numbers are truthy except for 0.
0 || 4; // 4
2 || 3; // 2 (picks the first one, because both true)
-3 || 0; // -3
0 || -2; // -2
Does it converts integers in bytes and performs or operation?
No. The || operator is logical and, not bitwise and.
Just wondering if anyone has come across this before.
I found in a project (that was handed over from another developer) a conditional statement that looked something like this:
if (variableOne == true | variable2 == true) {
// Do something here
}
It didn't error, so seems to work. But, myself and a colleague have never seen an OR statement with a single pipe |, only 2 ||.
Can anyone shed light on this mystery?
Thanks,
James
This is a bitwise OR operator. It will first convert it into a 32 bit integer, then apply the bitwise OR operation to the two numbers that result. In this instance, since Boolean(1) is true and Number(true) is 1, it will work fine without issue (the == operator will always return a boolean, and a if statement converts anything to a boolean). Here are a few examples of how it works:
1 | 0; // 1
0 | 0; // 0
0 | 1; // 1
1 | 1; // 1
true | false; // 1
false | false; // 0
2 | 1; // 3 (00000010, 00000001) -> (00000011)
As both sides have to be converted to a number (and therefore evaluated), this may cause unexpected results when using numbers when the logical OR statement (||) was meant to be used. For this, take these examples:
var a = 1;
a | (a = 0);
console.log(a); // 0
var b = 1;
b || (b = 0);
console.log(b); // 1
// I wanted the first one
var c = 3 | 4; // oops, 7!
Reference: http://www.ecma-international.org/ecma-262/5.1/#sec-11.10
That's a bitwise OR, see the documentation from Mozilla: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators)
The two pipes syntax "||" means it short circuits the logical expression. Evaluating only the needed until it knows the result.
What does it means?
if(a==null || a.type=='ok')
If a is null, it will evaluate only the first part of the expression, without errors on javascript side.
if(a==null | a.type=='ok')
If a is null in this case, you will have an error, since it will evaluate the second part of the expression too.
It's the same thing on others C type languages: Java, C,C++
And the same thing applies to '&' and '&&'
| is a bitwise OR, which in some very limited cases can substitute the ||.
An important difference is that with | both operands are evaluated, unlike with the || which evaluates the second operand only if the first is false.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
I'm looking at some Javascript code that is:
if ( a>2 | b>4 ) { ... }
(ignore the ... above). What's the | doing? I assume it's logical OR, but all the references I could find online speak about ||, and I can't find anything mentioning just |. Thanks in advance
It's the bitwise or. || is logical or.
The bitwise or (|) coerces the values to 32 bit integers and returns the 32 bit integer with each bit set to 1 if either of the two bits in the corresponding locations is 1 and 0 if they are both 0.
Logical or (||) evaluates to the first value if it's not falsey, otherwise it evaluates to the second value.
You almost definitely want || instead of |.
The difference between || and | is already explained in the other answers.
However, in the above code, | has the same effect as || due to type conversion.
true and false are mapped to 1 and 0 and we have
0 | 0 = 0
1 | 0 = 1
0 | 1 = 1
1 | 1 = 1
The same goes into the other direction, 1 evaluates to true and 0 to false.
So in this example,
if ( a>2 | b>4 )
will have the same result as
if ( a>2 || b>4 )
Note: This really only works with the two values 0 and 1.
This could be some kind of micro-optimization.
Update:
However, a short test reveals that using the bitwise OR for this purpose is way slower (at least in Chrome 9):
http://jsperf.com/js-or-test
Conclusion: Don't use it instead of logical OR :) Mostly likely someone forgot the second | and is just lucky that the code produces the same result.
Use boolean operators for boolean operations and bitwise operators for fancy bit masking. This might be worth reading: MDC - Bitwise Operators.
Single | is a bitwise-OR while double (||) is a logical-OR.
Bitwise-OR takes the binary representation of the two source values and ORs them together so that if either of the values has a bit set, the resulting value's bit will also be set (repeat for all the bits in the two source values).
Logical-OR concerns itself with true and false values (where 0 maps to false and non-zero maps to true - that's simplified, JavaScript has more specific rules). If either source value is true then the result is true.
Looks like second pipe just got lost, otherwise it is a smelly hack. See what really happens:
if ( Boolean( Number(a>2) | Number(b>4) ) ) { ... }
(Number is special here because bitwise operators are working with 32-bit integers)
It works because Number(true) === 1 && Number(false) === 0.