Javascript conditional statement with a single pipe "|" - javascript

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

Why does | work just like the || OR operator? [duplicate]

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

| vs || ... Does it matter which one I use? [duplicate]

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

what is this javascript expression for

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

Why does 1|0,2|0 equal 2 in JavaScript?

If you evaluate 1|0,2|0 in JavaScript, you'll get 2.
If you evaluate 1|0+','+2|0, you'll get 1.
I cannot make sense of this.
The binary bitwise operators (including |) bind less tightly than the addition operator +. Thus
1|0+','+2|0
is really
1|(0+','+2)|0
which is
1|('0,2')|0
which is
1|0|0
which is 1. (The string "0,2" is converted to an integer; as a number it's NaN, but because NaN is a floating-point concept it turns into 0 when forced to be an integer.)
edit — as to the first expression, 1|0,2|0, that involves the JavaScript comma operator. The comma operator allows a list of separate, essentially independent (other than through side-effects) expressions to be "glued together" into something the parser will recognize as a single expression. When evaluated, each expression will be computed as it normally would be, but the value of the overall expression is just the value of the last one in the list. Thus, 1|0,2|0 will first cause 1|0 to be evaluated, but that result is thrown away and the overall value is just that of 2|0.
The comma operator is common to many languages that derive their expression syntax from C. (For all I know, C got it from somewhere else; it's hardly a revolutionary concept.) Because such languages allow for an expression — just one expression — to appear in several interesting grammatical situations, and because expressions can (and often do) have side effects, it's sometimes handy to be able to jam several separate expressions into a spot where the language really wants only one. That said, there are often cleaner and better ways to do things. In JavaScript, I would personally prefer to use an immediately-invoked function. It's more typing and probably a little worse for performance reasons, but I think it's a lot cleaner because it allows for an isolated namespace for temporary variables and more involved logic.
You need to look at an operator precedence table to make sense of this.
The expression 1|0,2|0 has bitwise-or at a higher precedence than the comma operator, so it's equivalent to (1|0), (2|0). The comma operator evaluates both operands and returns the second one, so you get the value of (2|0). That value is 2.
The expression 1|0+','+2|0 has addition at a higher precedence than bitwise-or, so it's equivalent to 1|(0+','+2)|0. The result of 0+','+2 is "0,2", which is not numerical, so it evaluates to NaN in numerical operations. It is coerced to 0 in bitwise-or, so that leaves 1|0|0, and the result of that is 1.
From MDN:
The comma operator evaluates both of its operands (from left to right)
and returns the value of the second operand.
Thus, in 1|0,2|0, first the two expressions 1|0 and 2|0 are evaluated from left to right and then the result of the last expression (2|0) is returned. 1|0 === 1 and 2|0 === 2, so the result of the last expression is 2 and that's returned.
In 1|0+','+2|0, the comma appears in a string literal which is concatenated with 0 and 2. The whole thing is evaluated as followed:
( 1 | ( (0+',')+2 ) ) | 0
( 1 | ( '0,'+2 ) ) ) | 0 (number + string = string concatenation)
( 1 | '0,2' ) | 0 (string + number = string concatenation)
( 1 | NaN ) | 0 (bitwise OR needs number operands. 0,2 fails to be converted, giving NaN instead)
1 | 0 (bitwise OR only deals with integers, so the floating-point NaN is cast to 0)
1

Javascript: what's difference between | and ||?

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.

Categories