JS Loops (while) šŸŽÆ

beginner
9 min

JS Loops (while) šŸŽÆ

Welcome back to CodeYourCraft! Today, we're diving into the world of JavaScript loops, focusing on the while loop. This powerful tool will help you automate repetitive tasks in your code, making your life easier and your scripts more efficient.

What is a while loop? šŸ’”

A while loop is a control structure that allows you to repeatedly execute a block of code as long as a specific condition is true. In JavaScript, the basic structure of a while loop looks like this:

javascript
while (condition) { // code to be executed }

How does it work?

The while loop starts by checking the condition. If the condition is true, the code block inside the loop will execute. After the code block finishes, the loop goes back to the beginning and checks the condition again. This process continues until the condition becomes false.

šŸ“ Note: The condition is initially checked before the loop starts, which means the code block might execute zero times if the initial condition is false.

Practical Example šŸ“

Let's create a simple example where we print numbers from 1 to 10 using a while loop:

javascript
let counter = 1; while (counter <= 10) { console.log(counter); counter++; // increment the counter }

Breaking out of a while loop šŸ“

In some cases, you might want to break out of a while loop early. To do this, you can use the break statement. Here's an example where we break the loop when the counter reaches 5:

javascript
let counter = 1; while (counter <= 10) { console.log(counter); if (counter === 5) { break; } counter++; }

Quiz šŸ“

Quick Quiz
Question 1 of 1

What is the purpose of a `while` loop in JavaScript?

Stay tuned for more on while loops, and remember, learning to code is a journey, so take your time and have fun! šŸŽ‰