Incrementing & Decrementing Operators βž•βž–

In JavaScript, incrementing and decrementing are operations used to increase or decrease a variable’s value by 1. These operators are ++ (increment) and -- (decrement).

Example:

let x = 5;
x++; // Increment by 1, x becomes 6
x--; // Decrement by 1, x becomes 5

While Loops πŸ”„

A while loop repeatedly executes a block of code as long as the given condition evaluates to true.

Example:

let i = 0;
while (i < 5) {
console.log(i); // Outputs: 0, 1, 2, 3, 4
i++;
}

For Loops πŸ”„

A for loop is a more compact and commonly used loop, ideal for iterating over arrays or performing a fixed number of iterations. It consists of three parts: initialization, condition, and increment/decrement.

Example:

for (let i = 0; i < 5; i++) {
console.log(i); // Outputs: 0, 1, 2, 3, 4
}

Nested Iteration πŸ”

Nested loops involve placing one loop inside another. They are useful for iterating over multi-dimensional arrays or performing more complex iterations.

Example:

for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(i, j); // Outputs pairs of i and j
}
}

Break & Continue πŸ›‘βž‘οΈ

  • break is used to exit a loop prematurely.
  • continue is used to skip the current iteration and move to the next one.

Example (Break):

for (let i = 0; i < 5; i++) {
if (i === 3) break; // Stops the loop when i equals 3
console.log(i); // Outputs: 0, 1, 2
}

Example (Continue):

for (let i = 0; i < 5; i++) {
if (i === 3) continue; // Skips when i equals 3
console.log(i); // Outputs: 0, 1, 2, 4
}

Iterating Data Structures: Arrays πŸ—οΈ

You can use loops to iterate over arrays in JavaScript. Arrays are ordered collections, and each item can be accessed by its index.

Example:

let colors = ["Red", "Blue", "Green"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]); // Outputs: Red, Blue, Green
}

Iterating Data Structures: Objects πŸ—‚οΈ

Objects in JavaScript are collections of key-value pairs. To iterate over an object, you can use for...in or Object.keys().

Example using for...in:

let person = { name: "Alice", age: 25, city: "New York" };
for (let key in person) {
console.log(key + ": " + person[key]); // Outputs: name: Alice, age: 25, city: New York
}

Example using Object.keys():

let person = { name: "Alice", age: 25, city: "New York" };
Object.keys(person).forEach(key => {
console.log(key + ": " + person[key]); // Outputs: name: Alice, age: 25, city: New York
});

Conclusion: Mastering JavaScript Iteration πŸš€

JavaScript iteration allows you to loop through arrays, objects, and more, making it easier to handle collections of data. Whether using simple loops or advanced techniques like nested loops and for...in, mastering iteration is essential for any JavaScript developer. Keep practicing, and soon you’ll be iterating like a pro! πŸš€