JavaScript Bitwise
Bitwise operators treat numbers as a sequence of 32 bits and operate on them bit-by-bit. They can perform operations like AND, OR, XOR, and shifts, useful for low-level manipulation or optimization.
Key Topics
Common Bitwise Operators
Operators include: &
(AND), |
(OR), ^
(XOR), ~
(NOT), <<
(left shift), >>
(sign-propagating right shift), and >>>
(zero-fill right shift).
AND, OR, XOR
a & b
performs bitwise AND, a | b
bitwise OR, and a ^ b
bitwise XOR on the binary representations of a and b.
console.log(5 & 3); // 0101 & 0011 = 0001 (1)
console.log(5 | 3); // 0101 | 0011 = 0111 (7)
console.log(5 ^ 3); // 0101 ^ 0011 = 0110 (6)
Output
> 1
> 7
> 6
Explanation: Binary operations yield results based on bit patterns.
Bit Shifts
Shifts move bits left or right. a << n
shifts bits left n positions (multiply by 2n), a >> n
shifts right preserving sign, and a >>> n
shifts right filling with zeros.
JavaScript Usage in DOM
Bitwise operations are less common in DOM manipulation, but can be used for efficient calculations or encoding/decoding data before displaying it on the webpage.
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Bitwise in DOM</title></head>
<body>
<h1>Bitwise Demo</h1>
<button onclick="showBitwise()">Compute</button>
<p id="display"></p>
<script>
function showBitwise() {
let val = (5 & 3);
document.getElementById("display").textContent = "5 & 3 = " + val;
}
</script>
</body>
</html>
Key Takeaways
- Bitwise Ops: Work at the binary level on 32-bit integers.
- Common Operators: & (AND), | (OR), ^ (XOR), ~ (NOT), <<, >>, >>>
- Numerical Tricks: Can speed certain calculations or encodings.
- DOM Integration: Rarely used directly, but can assist in numeric processing for UI.