I found out the hard way that bitwise operators on bools don't return bools in JavaScript. I thought it must be a bug, but I looked it up in the ECMAScript spec, and sure enough, it says that the bitwise operators return numbers, not bools. It doesn't say a word about the weirdness that results when you're using them on boolean values. Why is it done this way? I've used this technique for years in other languages, so I'm totally baffled why it does something different in JavaScript. Any ideas? Is it just because no one ever uses bitwise operators in this way (except me), or is there a technical reason? I can't imagine it would be hard to check the type and return a boolean.
For reference, the following code:
var found = false;
console.log(found, typeof(found));
found |= true;
console.log(found, typeof(found));
found = true;
console.log(found, typeof(found));
Produces the following output:
false 'boolean'
1 'number'
true 'boolean'
Edit:
By request, I have used this in C, C++, and I'm pretty sure PHP, although I wouldn't swear on it. Yes, I realize that C/C++ are typed, so it would be different internally. I'm just wondering why JavaScript would behave differently.
By request, an example of how I would typically use |=
var foundLowest = false;
for(var k = 0; k < someLength; ++k) {
foundLowest |= someFunctionThatReturnsTF(k);
}
if(foundLowest === true) {
/* do stuff */
}
|
or&
on boolean values?|=
with booleans?true | false
it'strue
, and at the end of the day if I want to know is the left or right part istrue
, I would use||
(logical OR) instead of|