Home >Web Front-end >JS Tutorial >How Does the Bitwise OR Operator \'|\' Work in JavaScript?
Bitwise Operations in JavaScript: Unveiling the Mystery of the Single Pipe ("|") Operator
The single pipe ("|") operator in JavaScript performs bitwise or operations, which are essential for manipulating individual bits within binary representations. Unlike logical operators like ||, which perform operations on boolean values, bitwise operators work directly on the binary representation of integers.
Specifically, the bitwise or operator "|" computes the logical disjunction of its two integer operands. This means that for each bit position in the binary representations of the operands, if at least one bit is 1, the result bit is 1.
a | b = (a_n OR b_n) FOR ALL n
However, since bitwise operations only make sense on integers, JavaScript truncates non-integer values to integers before performing the operation. This can lead to unexpected results, as demonstrated in the provided examples:
console.log(0.5 | 0); // 0 console.log(-1 | 0); // -1 console.log(1 | 0); // 1
In the first example, 0.5 is truncated to 0 before performing the bitwise or operation with 0. Since both operands are 0, the result is 0.
In the second example, -1 (in binary representation: 11111111111111111111111111111111) remains unchanged when performing the bitwise or operation with 0 (in binary representation: 00000000000000000000000000000000), resulting in -1.
In the last example, 1 (in binary representation: 00000000000000000000000000000001) again remains unchanged, resulting in 1.
Therefore, for integers, x | 0 simply returns x.
The above is the detailed content of How Does the Bitwise OR Operator \'|\' Work in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!