JS Bitwise Operations 🎯

beginner
24 min

JS Bitwise Operations 🎯

Welcome to our deep dive into JavaScript (JS) Bitwise Operations! This tutorial is designed to help you understand and master this powerful programming concept, even if you're a beginner. By the end of this lesson, you'll be able to use bitwise operations effectively in your own projects. 💡 Pro Tip: Bitwise operations can optimize your code and make it more efficient, so let's get started!

Understanding Bitwise Operations 📝

Bitwise operations manipulate individual bits (binary digits) of a number. In JavaScript, numbers are stored as 64-bit floating-point values. However, when used in bitwise operations, they are treated as 32-bit integers.

The Bitwise Operators ✅

Here's a list of the six bitwise operators in JavaScript:

  • Bitwise NOT (~): Flips all the bits of a number.
  • Bitwise AND (&): Returns 1 only if both bits are 1.
  • Bitwise OR (|): Returns 1 if either or both bits are 1.
  • Bitwise XOR (^): Returns 1 if exactly one of the bits is 1.
  • Bitwise SHIFT Left (<<): Shifts the bits to the left by a specified number.
  • Bitwise SHIFT Right (>>): Shifts the bits to the right by a specified number.

Demystifying Bitwise Operations with Examples 💡

Let's explore these operators with some practical examples.

Example 1: Bitwise NOT (~)

javascript
// Original number let num = 60; // Applying Bitwise NOT let notNum = ~num; console.log('Original number:', num); console.log('Not of the number:', notNum);

Output:

Original number: 60 Not of the number: 11111111111111111111111011101000

Example 2: Bitwise AND (&)

javascript
// Original numbers let num1 = 13; let num2 = 5; // Applying Bitwise AND let andResult = num1 & num2; console.log('First number:', num1); console.log('Second number:', num2); console.log('Result of AND:', andResult);

Output:

First number: 13 Second number: 5 Result of AND: 1

Practice Time 💡

Quick Quiz
Question 1 of 1

What is the result of `11 & 3` in JavaScript?

Up Next 🚀

In our next lesson, we'll dive deeper into bitwise operations, learn how to perform shifts, and explore real-world applications of these powerful tools in JavaScript programming. Stay tuned! 📝 Note: Understanding bitwise operations will make your code more efficient and versatile, giving you an edge in your coding journey. 🚀

Happy coding! 🎉