Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of "|" (pipe) symbol in a JS array

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?

like image 513
shiv2685 Avatar asked May 20 '15 13:05

shiv2685


2 Answers

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)];
like image 117
Denys Séguret Avatar answered Nov 02 '22 23:11

Denys Séguret


| 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
Explanation: Lets take

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
like image 43
Amit Avatar answered Nov 02 '22 22:11

Amit