As others have pointed out, this is a bitwise OR operator. However, I don’t think that people use it a lot in numeric values in Javascript as usual - you do not do a lot of computation in Javascript. To give you a better idea of why this statement is useful, consider a much more common scenario that a user must fill out with at least one of several text fields.
Let's say you have this HTML code:
<input type="text" class="phone-nr" id="home-phone-nr-1" /> <input type="text" class="phone-nr" id="home-phone-nr-2" /> <input type="text" class="phone-nr" id="home-phone-nr-3" /> <input type="text" class="phone-nr" id="mobile-phone-nr-1" /> <input type="text" class="phone-nr" id="mobile-phone-nr-2" /> <input type="text" class="phone-nr" id="mobile-phone-nr-3" />
The user has the opportunity to fill out several phone numbers, but will have to provide at least one.
The easiest way to do this (with jQuery in this case):
var valid = false; $('.phone-nr').each(function(i, item){ valid |= $(item).val(); });
valid will be true if at least one input field with the phone-nr class has a non-empty value.
If each field needs to be filled out (a more general requirement), you can do this as follows with the bitwise AND operator:
var valid = true; $('.phone-nr').each(function(i, item){ valid &= $(item).val(); });
valid will only be true if the input fields all have a value.
If you need to fill in at least one field, but not more than one , you can use the XOR operator:
var valid = false; $('.phone-nr').each(function(i, item){ valid ^= $(item).val(); });
This, in my opinion, is the real use of bitwise operators in Javascript.
JulianR Oct 26 2018-10-26 15:16
source share