I have a JS array which is being used as follows in our existing code:
temp = charArray[0 | Math.random() * 26];
Wanted to know what exactly is the usage of "|" symbol in the above code and are there more such operators?
From the MDN:
Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.
As the 32 bit part is (a part of) the integer part of the IEEE754 representation of the number, this is just a trick to remove the non integer part of the number (be careful that it also breaks big integers not fitting in 32 bits!).
It's equivalent to
temp = charArray[Math.floor(Math.random() * 26)];
| is bitwise OR, which means, that all bits that are 1 in either of the arguments will be 1 in the result. A bitwise OR with 0 returns the given input interpreted as an integer.
In your code the its majorily used to convert the Math.random() number to integer. The bottom line is :
var a = 5.6 | 0 //a=5
var a = 5; //binary - 101
var b = 6; //binary - 110
a|b a|a a|0
101 101 101
110 101 000
------ ------ ------
111-->7 101-->5 101-->5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With