JavaScript: why does the bitwise OR from booleans return a number instead of a boolean?

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) { /* do stuff */ } 
+5
source share
1 answer

If bitwise operators behave sequentially (always convert their operands to numbers), they seem to be a good enough reason to indicate them as they are. A few years ago, in the discussion list, the question of adding ||= and similar abbreviated operators was discussed, but Eich & Co is very conservative with regard to adding such things, and I seem to recall the comment in accordance with the fact that he β€œdid not pull out his syntactic weight ".: -)

Please note that since JavaScript gladly forces any value to a boolean, you can happily use your current style and still work, because true leads to 1 , which forces to true and false coerces to 0 , which approaches false . For instance:.

 var a = false; a |= true; // Even though `a` is now `1`, it works just fine if (a) { snippet.log(a + " => if branch"); // Does this one } else { snippet.log(a + " => else branch"); } a &= false; // Even though `a` is now `0`, it works just fine if (a) { snippet.log(a + " => if branch"); } else { snippet.log(a + " => else branch"); // Does this one } 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.imtqy.com/simple-snippets-console/snippet.js"></script> 
+6
source

Source: https://habr.com/ru/post/1209620/


All Articles