TIL about JavaScript’s |= Operator
¶ by Rob FrieselToday, while exploring Larry Myers’ jasmine-reporters extensions for Jasmine, I encountered something that I’d never seen before:
// bail when all pages have been processed | |
setInterval(function(){ | |
var exit_code = 0; | |
for (i = 0, l = pages.length; i < l; i++) { | |
page = pages[i]; | |
if (page.__exit_code === null) { | |
// wait until later | |
return; | |
} | |
exit_code |= page.__exit_code; | |
} | |
phantom.exit(exit_code); | |
}, 100); |
(Source.)
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
And:
x |= 1
Of course, the question that I asked here 3 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 with 4 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.
- MSDN has a good explanation as well.[
]
- If you want to be a pedantic jerk, it’s a “bitwise inclusive OR assignment operator”.[
]
- Aside from Well how exactly does the bitwise OR work again?[
]
- Or even just “well-versed in”.[
]
Leave a Reply