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
Related
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
I have worked with javascript during 2 years now, but I have never seen an expression like this one. in google chrome console I have typed this
var a=456;
var b=789;
then I typed this
a|=b
and the result was 989
can someone tell me what is this expression for, and why is the result 989?
That is a bitwise OR operation. When used in that fashion it is "or equals" where the result is assigned to the variable.
111001000 //456
1100010101 //789
1111011101 //989
That expression is called bitwise or, with assignment. It takes the each individual bit position of each number, and returns a 1 for that bit if it is 1 at that position in either of the numbers, otherwise assigning 0 if both are 0.
See the Mozilla documentation for other such bitwise operations.
It is more commonly used in systems languages like C and C++.
well the expression
a|=b;
is like when you do a+=b; it's equivalent to
a = a | b;
the operator | is the OR, not like the operator ||. this one is used as the operator OR for binary operations
5 | 1 -> 0101 | 0001 -> 0101 -> 5
in your case
456 | 789 -> 111001000 | 1100010101 -> 1111011101 -> 989
I need to "translate" the following loop from JavaScript to Ruby:
for(i=0;i<=b.length-1;i++){
if(!(i%2)){
c+=b[i]
}
}
Here is how I tried to write the same in Ruby:
until i == b.length-1 do
unless i%2 == true
c += b[i]
i += 1
end
end
The modulus operator in Ruby, however, seems to return false all the time; which renders the whole condition meaningless.
What am I doing wrong?
You should have:
unless i%2 == 1
or, equivalently:
if i%2 == 0
The reason of unexpected behavior is that Ruby treats all values (including 0) except false and nil as "truthy" in conditional statements.
Both in JavaScript and Ruby the modulus operator is expected to return an integer not a boolean:
2 % 2
# => 0
3 % 2
# => 1
So, to check if i is even, you have to implement your condition like this:
unless i % 2 != 0
# ...
However, for the purpose I think it's better to use one of the methods Integer#even? and Integer#odd?:
if i.even?
#...
In Javascript, 0 and -0 are falsy values and therefore evaluate to false when doing comparisons. All other Numbers evaluate to true.
In Ruby, there is no implicit type conversion when comparing objects, and 0 evaluates to true. If you want to do your comparison in Ruby, you should use
if i%2 == 0
instead of your code.
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.