I found the following code in a JS project:
var a = new Array();
a[0] = 0;
for (var b = 0; b < 10; b++) {
a[0] |= b;
}
What does the |=
do in the body of the for loop?
The code example is dubious, but has been presented here by V8 for an example of improved performance.
Updated Example
The above example is equivalent to var a = [15];
for most intents and purposes. A more realistic example for the |=
operator would be to set up binary flags in a single variable, for example on a permission object:
//Set up permission masks
var PERMISSION_1_MASK = parseInt('0001',2);
var PERMISSION_2_MASK = parseInt('0010',2);
..
//Set up permissions
userPermissions = 0;
userPermissions |= hasPermissionOne && PERMISSION_1_MASK;
userPermissions |= hasPermissionTwo && PERMISSION_2_MASK;
..
//Use permissions
if(userPermissions & PERMISSION_1_MASK){
..//Do stuff only allowed by permission 1
}
is basically
"|" is an or bitwise operator (by the way: The MDN docs are really well written and really clear. If the OP is wanting to write and understand JS, then the MDN docs are a great resource.)
Update When
a[0]
is assigned0
,a[0]
in binary is0000
. In the loop,b = 0
b = 1
b = 2
b = 3
b = 4
b = 5
b = 6
b = 7
b = 8
b = 9
At the end of the loop the value of
a[0]
is15
Returns a one in each bit position for which the corresponding bits of either or both operands are ones.
Code: result = a | b;
^
is the bitwise XOR operator, which returns a one for each position where one (not both) of the corresponding bits of its operands is a one. The next example returns 4 (0100):is equivalent to
where
|
stands for bitwise OR.As with most assignment operators, it is equivalent to applying the operator using the lefthand value again:
Just like
Look on Moz Dev Net for more.
[Edit: Brain fail, mixed up | and ||. Need more coffee. Modified below]
Since
|
is the Bitwise OR operator, the result ofa|b
will be the integer representing the bitstring with all the 1 bits ofa
andb
. Note that javascript has no native int or bitstring types, so it will first casta
andb
to int, then do a bitwise OR on the bits. So 9 | 2 in binary is 1001 | 0010 = 1011, which is 11, but 8|2 = 8.The effect is to add the flag bits of
b
intoa
. So if you have some flagWEEVILFLAG=parseInt(00001000,2)
:will set that bit to 1 in a.