JavaScript Loops

 Fantastic! Let's explore Loops, which are one of the most powerful tools in programming for automating repetitive tasks.

🔁 Loops: Repeating Actions

Loops allow you to execute a block of code multiple times based on a condition. This saves you from writing the same code over and over.

1. The for Loop

The for loop is the most common and is ideal when you know exactly how many times you want to repeat an action. It has three parts, separated by semicolons, inside the parentheses:

 * Initialization: Executed once at the start (e.g., let i = 0).

 * Condition: Checked before every iteration. If it's true, the loop continues. If false, the loop stops (e.g., i < 5).

 * Final Expression (Increment/Decrement): Executed after every iteration (e.g., i++).

<!-- end list -->

// Example: Counting from 0 to 4

for (let i = 0; i < 5; i++) {

  console.log("Current count: " + i);

}


/* Output:

Current count: 0

Current count: 1

Current count: 2

Current count: 3

Current count: 4

*/


2. The while Loop

A while loop continues to execute a block of code as long as its condition remains true. You must ensure that something inside the loop changes the condition, or you'll create an infinite loop!

let countdown = 3;


while (countdown > 0) {

  console.log(countdown + "...");

  countdown--; // The key step: decreases 'countdown' so the loop eventually stops

}

console.log("Lift off! 🚀");


/* Output:

3...

2...

1...

Lift off! 🚀

*/


3. Loop Control Keywords

You can control the flow within any loop using these keywords:

 * break: Immediately stops the entire loop and continues execution with the code following the loop.

 * continue: Stops the current iteration and jumps to the next one (skips the rest of the current block).

<!-- end list -->

for (let i = 1; i <= 10; i++) {

  if (i === 5) {

    break; // Stop the loop entirely when i reaches 5

  }

  if (i % 2 !== 0) {

    continue; // Skip the rest of the code for odd numbers

  }

  console.log(i + " is an even number.");

}


/* Output:

2 is an even number.

4 is an even number.

(The loop breaks before 6 is checked)

*/


💡 Why Loops are Important

Loops are essential for working with collections of data, such as processing every item in a shopping cart, displaying a list of articles, or iterating over the characters in a string.

Now that you can make decisions (if/else) and repeat actions (loops), the next crucial step is to learn Functions—the mechanism for grouping code into reusable, named blocks.

Are you ready to learn about Functions?


Post a Comment

0 Comments