Search code examples
javascripttypescriptbooleanvariable-types

What is the meaning of "a|=b" in JS/TS if it's valid to begin with?


When I see the expression

let a : number = 3;
a = a + 5;

I immediately refactor it to

let a : number = 3;
a += 5;

and in both cases, the result is a===8 (I added the variable type for clarity). However, the boolean expression of the same pattern

let b : boolean = false;
b = b || true;

isn't equivalent to

let b : boolean = false;
b |= true;

as it produces a number. Now, the number correlates to true as it's a non-zero (and conversely, it corresponds to false in the opposite case as it returns zero). So there's a certain logic to that, of course.

It bugs me that I can't explain why it happens.

All the examples were executed in Chrome's console and I'm not entirely certain if the conversion to number from boolean occurs because of my operation or rendition in the browser or possibly something yet else.


Solution

  • | is a bitwise OR operation. || is the logical OR operation. |= is the compound bitwise OR assignment operator. There is no equivalent ||= operator for || in JavaScript (though there's been talk of adding it) and, so you can't do that refactoring with || (or &&), at least for now. (Well...you can if you use Babel, as there's a plugin for that proposal.)