JavaScript Bitwise Operators - Real World Examples (snippets) Number's Parity Detection with Bitwise AND

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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;
    }
}

You can do the parity check much more effective and simple:

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

(this is actually valid not only for JavaScript)



Got any JavaScript Question?