Numbers Parity Detection with Bitwise AND

suggest change

Instead of this (unfortunately too often seen in the real code) “masterpiece”:

function isEven(n) {
    return n % 2 == 0;
}

function isOdd(n) {
    if (isEven(n)) {
        return false;
    } else {
        return true;
    }
}

For an integer that fits in 32 bits, the low bit is enough. & first converts its operand with ToInt32, so a non-integer is truncated and a value outside that range can wrap:

if(n & 1) {
    console.log("ODD!");
} else {
    console.log("EVEN!");
}

Testing the low bit is a common technique. In JavaScript the & conversion is specifically ToInt32, and 1n & 1 throws because the operands have different numeric types.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents