Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 808
Leo Meo Avatar asked Aug 05 '14 01:08

Leo Meo


3 Answers

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
like image 61
Travis J Avatar answered Nov 15 '22 00:11

Travis J


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++.

like image 30
merlin2011 Avatar answered Nov 14 '22 23:11

merlin2011


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
like image 22
Khalid Avatar answered Nov 15 '22 00:11

Khalid