Posts.

Mastering Java Script | WHILE Loop

Cover Image for Mastering Java Script | WHILE Loop
Rami Al-Karo
Rami Al-Karo

Welcome back to our "Master JavaScript" course! Today, we embark on a journey to explore yet another fundamental concept in JavaScript – the `while` loop. Just like the `for` loop, the `while` loop is a versatile tool that empowers us to execute a block of code repeatedly based on a specified condition. Unlike its counterpart, the `for` loop, the `while` loop's iteration count relies solely on the condition. Let's dive into how it works and discover its practical applications.


Understanding the While Loop:

The `while` loop operates on a simple principle – it keeps executing the code block within its boundaries as long as the specified condition remains true. This characteristic makes it ideal for scenarios where the exact number of iterations is unknown, and you want to keep repeating the code block until a certain condition is met.

let i = 0; // Initialization while (i < 5) { // Condition console.log(i); // Code to be executed for each iteration i++; // Increment }

In this example, we initialise the variable `i` to 0. The loop will continue executing as long as the condition `i < 5` holds true. Inside the loop, we perform the desired operation – printing the value of `i` to the console. Then, we increment `i` using `i++`. The loop will keep repeating until the condition becomes false, ensuring we print the numbers from 0 to 4.


let sum = 0; let number = 1; while (number <= 10) { sum += number; number++; } console.log("The sum of numbers from 1 to 10 is:", sum);

In this second example, we want to find the sum of numbers from 1 to 10. We initialise the `sum` variable to 0 and the `number` variable to 1. The `while` loop will execute until `number` is less than or equal to 10. Within each iteration, we add the current `number` to the `sum` and then increment `number` by 1. The loop continues until `number` becomes 11, at which point the condition `number <= 10` becomes false, and the loop terminates. The result, displayed in the console, is the sum of numbers from 1 to 10.


Conclusion:

The `while` loop is a powerful and flexible construct in JavaScript. It allows us to handle various scenarios where we need to repeat code until a specific condition is met. By mastering the `while` loop, you'll gain the ability to tackle diverse challenges and build more dynamic and responsive JavaScript programs. Continue your learning journey, practice different loop patterns, and become a proficient JavaScript developer.


More Stories

Cover Image for  5 Array Methods in JavaScript | Part 3 | Mastering JavaScript

5 Array Methods in JavaScript | Part 3 | Mastering JavaScript

485 words - 2,754 characters

Rami Al-Karo
Rami Al-Karo
Cover Image for 5 Array Methods | Part 2 | Mastering JavaScript

5 Array Methods | Part 2 | Mastering JavaScript

907 words - 5,716 characters

Rami Al-Karo
Rami Al-Karo