Introduction to Bitwise Operators in JavaScript

Bitwise operators may seem obscure and a bit arcane to many developers. However, they are powerful tools for performing operations at the binary level. Their usage isn’t quite as common as arithmetic or logical operators, but understanding how they work will indeed allow you to leverage new abilities.

In this article, we’re going to explore these bitwise operators in JavaScript. Let’s get started.

First, what are bitwise operators?

Bitwise operators are operators that allow us to perform operations on binary representations of numerical values. They treat their operands as a sequence of 32 bits (0s and 1s), rather than as decimal, hexadecimal, or octal numbers. In JavaScript, we have access to several bitwise operators, including:

Operator Description
AND (&) Returns a 1 in each bit position where both operands have a 1.
OR (|) Returns a 1 in each bit position where at least one of the operands has a 1.
XOR (^) Returns a 1 in each bit position where only one of the operands has a 1.
NOT (~) Inverts the bits of its operand, converting 1s to 0s and vice versa.
Left Shift («) Shifts the bits of the first operand to the left by the number of positions specified by the second operand.
Right Shift (») Shifts the bits of the first operand to the right by the number of positions specified by the second operand. It preserves the sign bit when shifting.
Zero-fill Right Shift (»>) Similar to the sign-propagating right shift, but fills the leftmost bits with zeros.

Practical Applications

Bitwise operators are useful for low-level manipulation of binary data.

They can efficiently set, clear, or toggle specific bits within a binary number. This capability is important in scenarios such as network protocols, cryptography, and device drivers.

One common use of bitwise operators is to manage flags or permissions. By assigning each flag or permission a unique position in a binary number, bitwise operations can easily enable, disable, or check the status of individual flags. Let’s look at an example below.

const READ = 1;   // 0001
const WRITE = 2;  // 0010
const EXECUTE = 4; // 0100

let permissions = 0; // No permissions initially
permissions |= READ; // Grant read permission
permissions |= WRITE; // Grant write permission

if (permissions & READ) {
    console.log("Read permission granted.");
}

if (!(permissions & EXECUTE)) {
    console.log("Execute permission not granted.");
}

Bitwise operations can also increase performance in certain scenarios, especially when dealing with large datasets or optimizing algorithms. They are often faster than their arithmetic counterparts, making them preferable for specific computational tasks.

For example, check out this function that checks whether or not a number is even:

function isEven(num) {
    return (num & 1) === 0;
}

console.log(isEven(4)); // true
console.log(isEven(7)); // false

You might have never seen this way of checking for even or odd numbers. How does it work?

Well, imagine we have a special game where each number has its own special tag, kind of like a secret code.

Now, in this game, we have a rule for deciding if a number is even or not. We look at the last digit of the number’s code. If it’s 0, we say “even”, but if it’s 1, we say “odd”.

Now, let’s take any number. What we’re doing in the game is checking that last digit of its code. We use a special trick called “bitwise AND”, which is like asking a question: “Hey, what’s the last digit of your secret code?” And then we compare it with 0.

So, if the last digit (or bit, as we call it) of the number’s code is 0, it means the number is even, because it matches our rule. But if it’s 1, then the number is odd, because it doesn’t match our rule.

So, to check if a number is even in this game, we just use the trick of asking the number what its last digit is, and we compare it with 0. If they match, it’s even! And if they don’t, it’s odd.

Simple, right?

Conclusion

While bitwise operators in JavaScript might appear esoteric at first glance, mastering them can unlock powerful capabilities for manipulating binary data, managing flags, and optimizing performance.

Understanding these operators and their practical applications, allows us to write more efficient code and tackle a broader range of programming challenges.

Whether you’re working on low-level systems programming or optimizing algorithms, bitwise operators are essential tools in your toolbox.

comments powered by Disqus

Related Posts

Solving a Common Interview Question: the Two Sum Algorithm in JavaScript

Imagine you’re at a lively party, and everyone is carrying a specific number on their back. The host announces a game – find two people whose numbers add up to the magic number, and you win a prize!

Read more

Remove Duplicates from Arrays and Strings in JavaScript

Removing duplicates is a common problem in programming that can arise in various contexts, such as cleaning up data or ensuring unique entries.

Read more

Remote First: 5 Websites for Remote Job Opportunities

Would you prefer to work in an office, or while sitting at a beach somewhere in Thailand (i.e. remotely)? Okay, maybe there’s no beach in this scenario, but there’s definitely silence, and maybe your cat.

Read more