What does this expression mean in JS?
Value |= this.value
What does this expression mean in JS?
Value |= this.value
This will perform a bitwise OR between the bits in this.value
and the bits already stored in Value
, then store the result back into Value
.
var Value = 42; // 00101010
Value |= 96; // 01100000
window.alert(Value); // 01101010 -> 106
It's a bitwise or assignment operator, similar to +=
. If you run a test on it like this:
<ol>
<script language="javascript">
var x=false;
document.writeln("<li>"+x+"</li>");
x|=true;
document.writeln("<li>"+x+"</li>");
x&=false;
document.writeln("<li>"+x+"</li>");
</script>
</ol>
You'll get this output (in IE)
1.false
2.1
3.0
Essentially, x|=y
is the same as saying x=x|y
As others have pointed out, this is the bitwise OR operator. However, I don't think people use it much on numerical values in Javascript as - generally - you don't do a lot of computation in Javascript. To give you a better idea why this operator is useful, consider the far more common scenario that the user needs to fill in at least one of multiple textfields.
Say you have this HTML:
<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 option to fill in multiple phone numbers, but will have to supply at least one.
The easiest way to do this (with jQuery in this case) is:
var valid = false;
$('.phone-nr').each(function(i, item){
valid |= $(item).val();
}); // untested code
valid
will be true if at least one input field with class phone-nr
has a non-empty value.
If every field must be filled in (a more common requirement) you can do it like this with the bitwise AND operator:
var valid = true;
$('.phone-nr').each(function(i, item){
valid &= $(item).val();
}); // untested code
valid
will only be true if all input fields have a value.
If at least single field is required to be filled in, but no more than one you can use the XOR operator:
var valid = false;
$('.phone-nr').each(function(i, item){
valid ^= $(item).val();
}); // untested code
Those are, in my opinion, the real-world uses of bitwise operators in Javascript.