0

I'm trying to find an array element using binary search in javascript and I came across this block of code. I just started learning javascript just one week now. What does the character "|" mean in this statement

while (init_num <= last_num) {
            mid_point = (init_num + last_num) / 2 | 0;
}
Oluwole
  • 11
  • init_num is the index of the first element in the array, last_num is the index of the last element in the array for each loop of the search – Oluwole Oct 20 '16 at 06:54
  • __[Bitwise OR](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_OR)__ – Pranav C Balan Oct 20 '16 at 06:55

3 Answers3

1

It's a bitwise OR operator. But what it's doing there is using side-effects to make a number which may have a fractional portion a whole number instead.

All numbers in JavaScript are floating-point, so (init_num + last_num) / 2 may have a fractional portion. When you apply a bitwise operator to a number, it's temporarily coerced to a 32-bit integer, losing any fractional portion. Since the OR operator's result has a bit set for any bit set on either operand, and since the second operand in your example is 0 (all bits off), the result is the same bit pattern as the left-hand operand (which is then turned back into a floating-point number).

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
0

The pipe is a bitwise or.

One use of bitwise operators are numerical convertions, because sometimes they're much faster than their Math or parseInt equivalents. The price you pay is some code readability.

More information can be found here:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators

GibboK
  • 64,078
  • 128
  • 380
  • 620
0

| stands for OR example: x = 5 | 1 0101 | 0001 0101 = 5

also have a look at this: js comparisons

Kevin Kloet
  • 1,076
  • 1
  • 11
  • 21