found drama

get oblique

TIL about JavaScript’s |= Operator

by Rob Friesel

Today, while exploring Larry Myers’ jasmine-reporters extensions for Jasmine, I encountered something that I’d never seen before:


Did you see it, too? I saw it because my editor didn’t highlight it as an operator like I was expecting it to. What is this |=? I wondered. I scratched my head. Is that right? Is this some kind of error? But the script ran, and it ran fine. Surely this was a gap in my knowledge.

I took a closer look at it. Was this |= some kind of bitwise operator?

I turned to MDN’s page on assignment operators for my answer.1 Sure enough, |= was indeed a real thing: the bitwise OR assignment operator.2

It works just like you think it would, which is just like the other compound assignment operators. In other words, these statements are equivalent:

x = x | 1


x |= 1

Of course, the question that I asked here3 was: Was this the most idiomatic way to do this?

I thought maybe it wasn’t–if only because I don’t know too many JS devs that are intimately familiar with4 bitwise operators. Knowing what we know about JavaScript’s truthy/falsy values for numbers, this line:

exit_code |= page.__exit_code

…could just as easily have been this:

exit_code = page.__exit_code || exit_code

…but that’s not as succinct, and not necessarily as clear.

Granted, “not necessarily as clear” assumes that you know what | is good for in the first place. And I’ll be honest here: I’m still bitwise-na├»ve, so don’t look at me for deep and rigorous answers there. But if I was able to figure out this much in fifteen minutes this afternoon, then it’s at least not a completely foreign entity. And that’s good enough for me.

  1. MSDN has a good explanation as well. []
  2. If you want to be a pedantic jerk, it’s a “bitwise inclusive OR assignment operator”. []
  3. Aside from Well how exactly does the bitwise OR work again? []
  4. Or even just “well-versed in”. []

About Rob Friesel

Software engineer by day, science fiction writer by night. Author of The PhantomJS Cookbook and a short story in Please Do Not Remove. View all posts by Rob Friesel →

Leave a Reply

Your email address will not be published. Required fields are marked *