0% found this document useful (0 votes)
2 views10 pages

Day2 - Bitwise Operators in JavaScript

The document explains bitwise operators in JavaScript, detailing their functionality and use cases, such as AND, OR, XOR, NOT, and shifts. It also covers looping structures, including for, while, do...while, for...in, and for...of loops, along with their syntax and examples. The document highlights the importance of these concepts in programming for tasks like data manipulation and control flow.

Uploaded by

jeevavaishnavi7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Day2 - Bitwise Operators in JavaScript

The document explains bitwise operators in JavaScript, detailing their functionality and use cases, such as AND, OR, XOR, NOT, and shifts. It also covers looping structures, including for, while, do...while, for...in, and for...of loops, along with their syntax and examples. The document highlights the importance of these concepts in programming for tasks like data manipulation and control flow.

Uploaded by

jeevavaishnavi7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Bitwise Operators in JavaScript

Bitwise operators work on binary numbers (0s and 1s).


They manipulate data at the bit level.
JavaScript converts numbers to 32-bit signed integers, performs the operation, and then
converts the result back to a JavaScript Number.

Why Bitwise Operators?


 Used in low-level programming, graphics, cryptography, networking, and optimization.
 Faster than arithmetic operations in some scenarios.

List of Bitwise Operators

Example (5 &
Operator Symbol Description Result
1)

AND & Sets each bit to 1 if both bits are 1 0101 & 0001 0001 (1)

OR | Sets each bit to 1 if any bit is 1 0101 | 0001 0101 (5)

XOR ^ Sets each bit to 1 if only one bit is 1 0101 ^ 0001 0100 (4)

NOT ~ Inverts all the bits (1 → 0, 0 → 1) ~0101 -(5 + 1) = -6

Shifts bits to the left, adding zeros from


Left Shift << 5 << 1 → 1010 10
the right

Shifts bits to the right, keeping the sign


Right Shift >> 5 >> 1 → 0010 2
bit (MSB)

Unsigned Right Shifts bits to the right, filling zeros Large


>>> -5 >>> 1
Shift (ignores sign) positive

Binary Representation Example

Decimal Binary (4-bit)

5 0101

1 0001

4 0100

2 0010

1. Bitwise AND (&)


Returns 1 only if both bits are 1.
let a = 5; // 0101
let b = 1; // 0001
[Link](a & b); // Output: 1 (0001)
5 → 0101
3 → 0011
------------
& 0001 → 1

2. Bitwise OR (|)
Returns 1 if either bit is 1.
let a = 5; // 0101
let b = 1; // 0001
[Link](a | b); // Output: 5 (0101)
5 → 0101
3 → 0011
------------
| 0111 → 7

3. Bitwise XOR (^)


Returns 1 if bits are different, otherwise 0.
let a = 5; // 0101
let b = 3; // 0011
[Link](a ^ b); // Output: 6 (0110)
5 → 0101
3 → 0011
------------
^ 0110 → 6

4. Bitwise NOT (~)


Flips all bits and adds 1, giving the negative number.
let a = 5; // 0101
[Link](~a); // Output: -6
Formula:
~n = -(n + 1)
5 → 00000000 00000000 00000000 0000 0101
~5 → 11111111 11111111 11111111 1111 1010 → -6

5. Left Shift (<<)


Moves all bits left by a specified number of positions.
Adds zeros from the right.
let a = 5; // 0101
[Link](a << 1); // Output: 10 (1010)
Formula:
a << n = a * (2^n)
5 → 00000101
<<1 →0000 1010 → 10

6. Right Shift (>>)


Moves all bits right, keeping the sign bit (for negative numbers).
let a = 5; // 0101
[Link](a >> 1); // Output: 2 (0010)

let b = -5; // Negative number


[Link](b >> 1); // Output: -3
5 → 00000101
>>1 →00000010 → 2

7. Unsigned Right Shift (>>>)


Moves bits right, fills zeros, and ignores sign bit.
let a = -5;
[Link](a >>> 1);
// Output: 2147483645 (Large positive number)
-5 → 11111111 11111111 11111111 11111011
>>>1 →01111111 11111111 11111111 11111101 → 2147483645
Quick Comparison: >> vs >>>

Operator Negative Number Output

>> Keeps sign bit, stays negative

>>> Fills with zeros, becomes positive

Real-Time Example: Checking if a Number is Even/Odd


Using bitwise AND:
function checkEvenOdd(num) {
if (num & 1) {
[Link](num + " is Odd");
} else {
[Link](num + " is Even");
}
}
checkEvenOdd(10); // Output: 10 is Even
checkEvenOdd(7); // Output: 7 is Odd

Summary

Operator Use Case

& AND Masking, checking bit flags

` ` OR

^ XOR Toggling bits

~ NOT Inverting bits

<< Left Shift Multiplying by 2ⁿ

>> Right Shift Dividing by 2ⁿ (keeps sign)

>>> Unsigned Right Shift Logical shift ignoring sign


Looping in JavaScript
Loops are control structures that allow you to execute a block of code repeatedly as long as a
condition is true.
They help to:
 Reduce code repetition
 Automate tasks
 Iterate through arrays, strings, objects, etc.

Types of Loops in JavaScript

Loop Type When to Use

for loop When the number of iterations is known.

When the number of iterations is unknown, but the condition must be checked
while loop
first.

do...while loop When the loop must run at least once, then check the condition.

for...in loop To iterate through object properties.

for...of loop To iterate through iterable objects like arrays or strings.

1. for Loop
Used when you know beforehand how many times you want the loop to run.
Syntax
for (initialization; condition; update) {
// Code block
}
Flowchart
1. Initialize →
2. Check Condition →
3. Execute Code →
4. Update →
5. Repeat until condition is false.
Example: Print numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
[Link](i);
}
// Output: 1 2 3 4 5

2. while Loop
Runs as long as the condition is true.
The condition is checked first, then the loop body runs.
Syntax
while (condition) {
// Code block
}
Example: Print numbers from 1 to 5
let i = 1;
while (i <= 5) {
[Link](i);
i++;
}
// Output: 1 2 3 4 5
🔹 Use Case: When you don’t know how many iterations are needed, like user input validation.

3. do...while Loop
Similar to while, but runs at least once, even if the condition is false.
Syntax
do {
// Code block
} while (condition);
Example: Print numbers from 1 to 5
let i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
// Output: 1 2 3 4 5
🔹 Use Case: When you must execute the loop once before checking the condition, like menus
or login attempts.

4. for...in Loop (Objects)


Used to iterate through properties of an object.
Syntax
for (let key in object) {
// Code block
}
Example: Iterate over object properties
const student = { name: "Alice", age: 20, grade: "A" };

for (let key in student) {


[Link](key + ": " + student[key]);
}

// Output:
// name: Alice
// age: 20
// grade: A
🔹 Use Case: Accessing keys and values of objects.
5. for...of Loop (Iterables)
Used to iterate over iterable objects, like arrays or strings.
Syntax
for (let element of iterable) {
// Code block
}
Example: Iterate over an array
const fruits = ["Apple", "Banana", "Mango"];
for (let fruit of fruits) {
[Link](fruit);
}
// Output: Apple Banana Mango
Example: Iterate over a string
let str = "JS";
for (let char of str) {
[Link](char);
}
// Output:
// J
// S
🔹 Use Case: Working with arrays, strings, and other iterables.

6. Nested Loops
A loop inside another loop.
Example: Multiplication Table
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
[Link](`${i} x ${j} = ${i * j}`);
}
}
7. break and continue

Keyword Purpose

break Stops the loop immediately.

continue Skips the current iteration and moves to the next one.

Example: Using break


for (let i = 1; i <= 5; i++) {
if (i === 3) break;
[Link](i);
}
// Output: 1 2
Example: Using continue
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
[Link](i);
}
// Output: 1 2 4 5

Comparison Table

Feature for loop while loop do...while loop

Condition Check Before execution Before execution After execution

Runs At Least Once? ❌ No ❌ No ✅ Yes

Use Case Known iterations Unknown iterations Execute once, then check

Real-Time Examples
1. Validate Password (while loop)
let password;
while (password !== "1234") {
password = prompt("Enter password:");
}
[Link]("Access Granted!");
2. Array Sum (for loop)
let numbers = [1, 2, 3, 4, 5];
let sum = 0;

for (let num of numbers) {


sum += num;
}
[Link]("Sum = " + sum);
// Output: Sum = 15

3. Display Menu (do...while loop)


let choice;
do {
[Link]("1. Add\n2. View\n3. Exit");
choice = parseInt(prompt("Enter your choice:"));
} while (choice !== 3);

[Link]("Exited Program");

Summary

Loop Type Use Case

for Known number of iterations

while Unknown iterations, condition checked first

do...while Must execute once before checking condition

for...in Iterate through object properties

for...of Iterate through arrays, strings, and other iterables

You might also like