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
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
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
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
This question already has answers here:
What do these JavaScript bitwise operators do?
(3 answers)
Closed 9 years ago.
I am trying to figure out this operator on JS -
'string' ^= 'string';
But I can not find ant information.
Is that a comparison or assignment ?
Thanks.
myVar ^= 5 is the same as myVar = myVar ^ 5. ^ is the bitwise xor operator
Let's say myVar was set to 2
5 in binary is: 101
2 in binary is: 010
Exclusive "or" checks the first bit of both numbers and sees 1,0 and returns 1 then sees 0,1 and returns 1 and sees 1,0 and returns 1.
Thus 111 which converted back to decimal is 7
So 5^2 is 7
var myVar = 2;
myVar ^= 5;
alert(myVar); // 7
^ (caret) is the Bitwise XOR (Exclusive Or) operator. As with more common operator combinations like +=, a ^= b is equivalent to a = a^b.
See the Javascript documentation from Mozilla for more details.
x ^= y is bitwise XOR and shorthand for x = x^y - and so is technically an "assignment" to answer your question. And to be precise the single operator '^' indicates the bitwise XOR.
As d'alar'cop (and several others by now) already pointed out, this means something called XOR. I always hate to read a wikipedia explanation, so I'm going to put another explanation here:
'XOR' means 'eXclusive OR'. What is that? First an example:
11000110 -- random byte
10010100
--------- ^ -- XOR
01010010
XOR is some bitwise operation, returning two if one of two bits is 1 and the other 0. If they're both 1, it's 'and', not 'exclusive or' ('normal or' would allow two 1's).
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.