I found that bitwise operators on bools do not return bools in JavaScript. I thought it was a mistake, but I looked at it in the ECMAScript specification and, of course, says that bitwise operators return numbers, not bools. He does not say a word about the strangeness that occurs when you use them according to logical values. Why is this done? I have used this technique for many years in other languages, so I am completely puzzled by why something else works in JavaScript. Any ideas? Is it simply because no one ever uses bitwise operators this way (except for me), or is there a technical reason? I cannot imagine that it would be difficult to check the type and return a boolean value.
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));
It produces the following output:
false 'boolean' 1 'number' true 'boolean'
Edit:
Upon request, I used this in C, C ++, and I'm sure PHP, although I will not swear it. Yes, I understand that C / C ++ is typed, so it will be different from the inside. I'm just wondering why JavaScript will behave differently.
Upon request, an example of how I usually used | =
var foundLowest = false; for(var k = 0; k < someLength; ++k) { foundLowest |= someFunctionThatReturnsTF(k); } if(foundLowest === true) { }
source share