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!
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.
Here's a list of the six bitwise operators in JavaScript:
~): Flips all the bits of a number.&): Returns 1 only if both bits are 1.|): Returns 1 if either or both bits are 1.^): Returns 1 if exactly one of the bits is 1.<<): Shifts the bits to the left by a specified number.>>): Shifts the bits to the right by a specified number.Let's explore these operators with some practical examples.
~)// 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
&)// 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
What is the result of `11 & 3` in JavaScript?
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! 🎉