➕bitwise not (~)
🚧 under construction -> code example
JS ⟩ statement ⟩ expression ⟩ operator ⟩ arithmetic ⟩ bitwise ⟩ not
(converts the operand to a 32-bit signed integer)
inverts the bits of its operand. (definition: ~x = -x - 1
, 👉 2's complement)
// ⭐ `~x` === -x - 1 (if x integer, truncate decimal if not)
~(3), // -4 (-3 - 1)
~(-5), // 4 ( 5 - 1)
~(3.4), // -4 ( 3.4 -> 3 -> -3 - 1 = -4)
~(-5.5), // 4 (-5.5 -> -5 -> 5 - 1 = 4)
// ⭐ `~~x`: nearest integer towards 0.
~~(7.8), // 7
~~(-3.4), // -3
~~(6), // 6 (⭐ `~~x = x`, if x integer)
replit: bitwise not (~) (v.2)
┌── (+x !== ~~x)
│
│ x type +x ~~x ~x ⭐
────────────────────────────────────────────────────────────────────
null Null 0 0 -1
⭐ undefined Undefined NaN 0 -1
────────────────────────────────────────────────────────────────────
true Boolean 1 1 -2
false Boolean 0 0 -1
────────────────────────────────────────────────────────────────────
'' String 0 0 -1
'23' String 23 23 -24
⭐ 'yes' String NaN 0 -1
────────────────────────────────────────────────────────────────────
1 Number 1 1 -2
0 Number 0 0 -1
⭐ NaN Number NaN 0 -1
⭐ Infinity Number Infinity 0 -1
⭐ -Infinity Number -Infinity 0 -1
────────────────────────────────────────────────────────────────────
⛔ 40n BigInt TypeError 40 -41
⛔ Symbol() Symbol TypeError TypeError TypeError
────────────────────────────────────────────────────────────────────
⭐ ({a:1}) Object NaN 0 -1
⭐ ({}) Object NaN 0 -1
────────────────────────────────────────────────────────────────────
[] Array 0 0 -1
⭐ [4.5] Array 4.5 4 -5
⭐ ['-7.8'] Array -7.8 -7 6
⭐ [1,2,3] Array NaN 0 -1
────────────────────────────────────────────────────────────────────
⭐ /regex/ RegExp NaN 0 -1
⭐ new Date Date 1667543819273 1096508425 -1096508426
⭐ ()=>{} Function NaN 0 -1
────────────────────────────────────────────────────────────────────
👉 double tilde (~~) - nearest integer towards 0.
replit: bitwise not (~)
// ⭐ test ~x
const M = 2 ** 32; // 4294967296
const m = M/8; // 536870912
M, // 4294967296
m, // 536870912 (m = M/8)
// ⭐ overflow: 3m + 2m ≡ -3m (mod M)
~~(5*m), // -1610612736 (overflow)❗
-3*m, // -1610612736
// ⭐ underflow: -5m ≡ 3m (mod M)
~~(-5*m), // 1610612736 (underflow)❗
3*m, // 1610612736
-5*m, // -2684354560
// ⭐ ~(x ± M) = ~x
~1234, // -1235
~(1234 - M), // -1235
~(1234 + M), // -1235
'----------',
// ⭐ `~x` === -x - 1 (truncate decimal if needed)
~(3), // -4 (-3 - 1)
~(-5), // 4 ( 5 - 1)
~(3.4), // -4 ( 3.4 -> 3 -> -3 - 1 = -4)
~(-5.5), // 4 (-5.5 -> -5 -> 5 - 1 = 4)
// ⭐ `~~x`:
~~(7.8), // 7 (⭐ nearest integer towards 0)
~~(-3.4), // -3
~~(6), // 6 (⭐ `~~x = x`, if x integer)
Last updated