Difference Between Single And Double Vertical Bar (|, ||) in JavaScript? [duplicate] - javascript

This question already has answers here:
What's the difference between ( | ) and ( || )?
(7 answers)
Closed 4 years ago.
For a while, I have used "||" as the "or" indicator. One day, I was debugging some things in a console, and I accidentally put a single | instead of two. It still worked as expected.
console.log(0||1); // 1
console.log(0|1); // 1
Is there any difference? Here, there evidently isn't, but there might be some hidden difference that I don't know about. I apologize if this is a duplicate, but I assure you I have looked for the answer beforehand.

That is called a bitwise OR, meaning it ORs the individual bits that compose a value based on binary rules.
a b a OR b
0 0 0
0 1 1
1 0 1
1 1 1
For your example, 0 in binary is just 0000, and 1 in binary is 0001.
Thus 0|1 is:
0000 | 0001
Which, when we apply the table above between each binary digit of the two numbers:
0 or 0 = 0
0 or 0 = 0
0 or 0 = 0
0 or 1 = 1
give us 0001, which when converted to decimal becomes 1.
The way || (logical OR) behaves is using coercion rules which returns the first truthy item (or just the last item) in a sequence of ||.
Since 0 is falsy, 0 || 1, will return 1.
Just because the answers happen to be the same in these two situations, does not mean that the operations always produce equal results.
For instance:
2|3 === 3
2||3 === 2

| is a bitwise OR.
Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1
|| is a logical OR.
In your example, 0|1 will evaluate to 1, because ... 0000 | ... 0001 evaluates to ... 0001.
0||1 will evaluate to 1 because 0 is falsy so it'll return the right operand 1

Related

Difference between (|) Bitwise OR vs (^) Bitwise XOR in JavaScript

I'm really getting confused on the use of the | OR vs ^ XOR in JavaScript, illustrated in the simple example below;
(function sayHi(n){
if(n < 1) //base case
return;
console.log("Hi!!" | "Hello!!") ;
sayHi(n - 1); //recurse
})(5);
(function sayHi(n){
if(n < 1) //base case
return;
console.log("Hi!!" ^ "Hello!!") ;
sayHi(n - 1); //recurse
})(5);
(function sayHi(n){
if(n < 1) //base case
return;
console.log(2 | 6) ;
sayHi(n - 1); //recurse
})(5);
(function sayHi(n){
if(n < 1) //base case
return;
console.log(2 ^ 6) ;
sayHi(n - 1); //recurse
})(5);
I'm confused about when, how, why, where I should appropriate use | vs ^.
Can someone please help me make sense the major difference between OR and XOR operations?
I was reading the documentation for JavaScript from MDN web Docs to better understand the concept of bitwise operations, but I am struggling to understand their significant difference.
I just want to make sure I continue to use these operations correctly henceforth.
Thanks a lot for the anticipated help!
OR and XOR are different operators:
OR:
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
XOR
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
If you have two bits and combine these with OR, the result will be 1, if one of these bits or both are 1. If you combine them with XOR (Exclusive OR) then it will be 1 if only one of these bits are 1 (not if both).
| is a bitwise or
So, if either bit is set in two operands, it will be set in the result
^ is an exclusive or, so if one bit is set in one of the operands, it will be set in the result, otherwise, it will not be set.
var x,y;
for (x = 0; x <= 1; x++) {
for (y = 0; y <= 1; y++) {
console.log('XOR '+ x + "^" + y + "=" + (x^y));
console.log('OR '+ x + "|" + y + "=" + (x|y));
}
}
Bitwise operators are typically used for checking whether a bit is set in a binary or not. You can vision it as a set of boolean values been compact it as a string 11100101, where each bit is used to represent the boolean flag true or false, 1 for set and 0 for unset respectively.
Binary reading is done abit different from our usual English. It is done from right to left, with the most left bit been the most significant bit because it holds the greatest value and the left hand side bit been the least.
Example:
Value: 64 = binary 10000000
Value: 1 = binary 00000001
Now back to your question.
Q: I'm confused about when, how, why, where I should appropriate use | vs ^.
A:
Bitmask and its operators are more commonly seen in low level programming where memory is a constraint (small computing device) or on performance critical application.
Sounds advantageous to use right? But they have their downside as well and it is code readability. Memory is cheap and processing power is much more greater than what it used to be, so people tend to forgo this bit of advantage when doing high level application programming.
Q: Can someone please help me make sense the major difference between OR and XOR operations?
OR and XOR operations are used for comparing two binaries. Let say binary A and binary B.
In layman term. The OR operations | can be read as if the bit in A OR B is set then return as set, which is 1.
Example:
10000000 // Value 64 in binary
00000001 // Value 1 in binary
10000001 // Gives you 65 when you perform | OR operation
= 65
XOR operation works a bit like OR but it has another special ability that is when two bits are the same it returns you 0 instead.
Example:
10000001 // Value 65 in binary
10000000 // Value 64 in binary
00000001 // Gives you 1 when you perform ^ XOR operation
= 1
From memory, you generally only use the AND & operator to check whether a bit is set or not. So you might be more interested in it and also the shift operations.
Your code doesn't make sense, bitwise operators (OR, XOR, AND) can only be used on numbers, not strings.
Each number is represent in memory by bits, each of which is 1 or 0 (true or false, on or off, etc). 1 and 0 are digits, just like 1, 2, 3, 4 are digits in our counting system. This counting system used by computers is called binary.
Bitwise operations basically perform the namesake operation (OR, XOR, or AND) on every single bit in the two operands.
Take 5 ^ 3 (5 XOR 3) for example:
5 is represented in binary as 00000101
3 is represented in binary as 00000011
For each operation, you have a left input, and a right input.
XOR stands for eXclusive OR, and returns 1 if the left OR the right input is 1, but not if they are both 1.
OR returns 1 if either of the inputs is 1, so if both are 1, then the output will also be 1.
A bitwise operation on a number performs this for every corresponding bit in each number, so 5 ^ 3 = 00000110, which is 6.
Note: Binary numbers are written from right to left. Each digit corresponds to a power of 2, like how digits correspond to powers of 10 when counting. The leftmost digit represents the highest power of 2 (in this case, 2 to the 7th, which is 128).
0 ^ 0 = 0 for the first 5 bits
1 ^ 0 = 1 for the 6th bit
0 ^ 1 = 1 for the 7th bit
1 ^ 1 = 0 for the 8th bit
Meanwhile, 5 | 3 = 00000111, which is 7.
0 | 0 = 0 for the first 5 bits
1 | 0 = 1 for the 6th bit
0 | 1 = 1 for the 7th bit
1 | 1 = 1 for the 8th bit
They are different math (logical) operators, more related to math than JavaScript.
OR / |, or called "Inclusive OR", is similar to the English phrase "A and/or B", there are 3 possibilities: not A but B, not B but A, both A and B.
XOR / ^, or called "Exclusive OR", is similar to the English phrase "either A or B", there are only 2 possibilities: not A but B, not B but A. You can see that "both A and B" is excluded, so called "exclusive".
Reference:
https://en.wikipedia.org/wiki/Logical_connective

Behavior of ^ in javascript

alert(15^2) - behaves as alert(15-2), alerts 13
alert(15^10) - behaves as alert(15-10), alerts 5
So it subtracts second number from the first, if the second number is smaller.
But if the second number is larger, for example
alert(15^16), it sums them, behaves as alert(15+16) and alerts 31.
alert(15^3^4) behaves as alert(15-3-4), so it alerts 8.
While
alert(15^3^2) behaves as alert(15-3+2), so it alerts 14.
Can anyone explain me this behavior?
It is called XOR. For each bit on each number it outputs a 1 if both are different.
1 XOR 0 = 1
0 XOR 1 = 1
1 XOR 1 = 0
0 XOR 0 = 0
So when you have the operation 15^2 you are doing:
1111 XOR
0010
----
1101
Which looks like a substraction, but for those special cases only.
As with the cases on multiple times, for example 15^3^4 = (15^3)^4 so you first calculate 15^3 and then the result with 4:
1111 XOR (15)
0011 (3)
----
1100 (12)
and then:
1100 XOR (12)
0100 (4)
----
1000 (8)
Therefore, 15^3^4 = 8.
That is a bitwise XOR operation you are doing, not powers.
According to MDN:
Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.
In javascript, you can use Math.pow to do the math operation.
So
alert(Math.pow(15, 2))
Shows a messagebox with the value 225.

Why is ~null === -1?

A questions that stumped me on this JavaScript test was that ~null evaluates to -1.
Why does ~null evaluate to -1?
That's because ~ is a numeric operator, so it casts null to 0 first:
> ~0
-1
It would be equivalent to this expression:
~(+null)
Likewise:
> ~[]
-1
> ~{}
-1
First of all, ~ is a bitwise NOT operator. That means it flips all the bits in the number representation. 0010 1010 becomes 1101 0101.
As a consequence of computers using 2's complement for storing numbers, this equality holds:
~number == -number - 1
As can be shown from my previous example:
0010 1010 (this represents number 42)
1101 0101 (this represents number -43)
Now, because ~ is an operator that operates on numbers, its argument gets cast to a number first. Since null gets cast to a 0, you get -1 as a result (according the above equation).

What's the function of the "|" (pipe) operator? [duplicate]

This question already has answers here:
Using bitwise OR 0 to floor a number
(7 answers)
Closed 8 years ago.
I have this line that I copied from another place:
Total += parseFloat($(this).val())|0;
What's the function of the operator |? When I change the number, I get different results.
The | in JavaScript is an integer bitwise OR operator. In that context, it strips off any fractional portion returned by parseFloat. The expression parseFloat($(this).val()) will result in a number with (potentially) a fractional component, but then |0 will convert it to an integer number, OR it with 0 (which means it won't change), and so the overall result is to get a whole number.
So functionally, it truncates the fractional portion off the number. -1.5 becomes -1, and 1.5 becomes 1. This is like Math.floor, but truncating rather than rounding "down" (Math.floor(-1.5) is -2 — the next lowest whole number — rather than -1 as the |0 version gives us).
So perhaps that's why it was used, to chop off (rather than "floor") the fractional portion of the number.
Alternately, it could be a typo. The author of that code might have meant to write this (note || rather than |):
Total += parseFloat($(this).val()) || 0;
That defends against the possibility that $(this).val() returns "" or similar, resulting in parseFloat returning NaN. It uses the curiously-powerful || operator to return 0 rather than NaN in that case. (And there's an advertisement for putting spaces around your operators.) Would have to know the context of the code to say whether truncating to a whole number (|) makes sense when adding to Total, or if they were just defending the NaN case.
The | operator in javascript is the bitwise or operator
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators
This operator treats the operands as 32 bit integers and for every bit returns 1 if either is 1 and 0 otherwise.

JavaScript | operator [duplicate]

This question already has answers here:
Using bitwise OR 0 to floor a number
(7 answers)
Closed 8 years ago.
Anyone able to explain what "|" and the value after does? I know the output for 0 creates sets of 13, the numbers, 3, 2, 1, 0. But what about | 1, or | 2.
var i = 52;
while(i--) {
alert(i/13 | 0);
}
It is the bitwise OR operator. There is both an explanation and an example over at MDC. Since doing bitwise OR with one operand being 0 produces the value of the other operand, in this case it does exactly nothing rounds the result of the division down.
If it were written | 1 what it would do is always print odd numbers (because it would set the 1-bit to on); specifically, it would cause even numbers to be incremented by 1 while leaving odd numbers untouched.
Update: As the commenters correctly state, the bitwise operator causes both operands to be treated as integers, therefore removing any fraction of the division result. I stand corrected.
This is a clever way of accomplishing the same effect as:
Math.floor(i/13);
JavaScript developers seem to be good at these kinds of things :)
In JavaScript, all numbers are floating point. There is no integer type. So even when you do:
var i = 1;
i is really the floating point number 1.0. So if you just did i/13, you'd end up with a fractional portion of it, and the output would be 3.846... for example.
When using the bitwise or operator in JavaScript, the runtime has to convert the operands to 32 bit integers before it can proceed. Doing this chops away the fractional part, leaving you with just an integer left behind. Bitwise or of zero is a no op (well, a no op in a language that has true integers) but has the side effect of flooring in JavaScript.
It's a bitwise operator. Specifically the OR Bitwise Operator.
What it basically does is use your var as an array of bits and each corresponding bit is with eachother. The result is 1 if any of them is 1. And 0 if both are 0.
Example:
24 = 11000
10 = 1010
The two aren't of equal length so we pad with 0's
24 = 11000
10 = 01010
26 = 11010
24 | 10 = 26
Best way to learn this is to readup on it.
That is the bitwise OR. In evaluating the expression, the LHS is truncated to an integer and returned, so | is effecively the same as Math.floor().

Categories

Resources