1

What does it do?

At first I thought it was a shorthand way of doing Math.max()
Every time I did (1 | 0) or (0 | 2985235), I got back the larger number.
However, I was wrong, as I soon found out when I posted this question with the example:
(128|256|0) which does not evaluate to 256.

Thanks for the helpful replies.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Joncom
  • 1,985
  • 1
  • 18
  • 29
  • 3
    `(128|256|0)` evaluates to 384. (← comment left before the question was rewritten; original question asked whether `(128|256|0)` is a "shorthand" for `Math.max(128, 256, 0)`.) – JJJ May 25 '13 at 09:34
  • Don't think so. And I just tried it in the console and I got 384. – aug May 25 '13 at 09:35
  • 2
    Read here https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators – elclanrs May 25 '13 at 09:35
  • 2
    It's a bitwise **OR** https://en.wikipedia.org/wiki/Bitwise_operation – Bart May 25 '13 at 09:37
  • http://stackoverflow.com/questions/5533387/javascript-operator, http://stackoverflow.com/questions/9472970/whats-the-function-of-the-pipe-operator, http://stackoverflow.com/questions/4535328/what-do-these-javascript-operators-do – JJJ May 25 '13 at 09:40
  • 3
    Please go back to documentation, always go back to the documentation if you're unsure about something. – Shane Hsu May 25 '13 at 09:41
  • 1
    @Juhana Yes, my bad. Google didn't bring up many relevant results when searching Javascript and the "|" character. – Joncom May 25 '13 at 09:42
  • @Joncom you should read this also: [What does “|=” mean?](http://stackoverflow.com/questions/14295469/what-does-mean-pipe-equal-operator) – Grijesh Chauhan May 25 '13 at 10:03
  • That's the problem with Google - unless you know the actual name of that symbol it's hard to find a corresponding result for a question on Google. – Qantas 94 Heavy May 25 '13 at 10:34

2 Answers2

3

| is a bitwise OR operator. To see what it does, consider the binary form of the numbers:

128 = 010000000
256 = 100000000
0   = 000000000

The result is from performing OR bit-by-bit

384 = 110000000

I guess you might encounter this pattern in the logic to represent options. For example,

128 = option 1
256 = option 2
384 = both option 1 & 2
Moritz Roessler
  • 8,542
  • 26
  • 51
Apiwat Chantawibul
  • 1,271
  • 1
  • 10
  • 20
2

| is a bitwise operator in Javascript. So before evaluating those integers, first convert them to binary.

  0 -> 000000000
128 -> 010000000
256 -> 100000000

There might be more preceding zeros depending on your data types. Anyway | as a bitwise OR operator, will evaluate each bit from those two integers.

So you will get 110000000 as an result, which is 384 in decimal.

P.S. OR operation: if any one of those hold true, then true.

Shane Hsu
  • 7,937
  • 6
  • 39
  • 63