JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - while loop

The while loop is a fundamental control flow statement in JavaScript that is used to execute a block of code repeatedly as long as a specified condition is true. Unlike the for loop, which is used when the number of iterations is known, the while loop is particularly useful in situations where the iterations need to continue until a certain condition changes, which may not be known ahead of time.

Imagine you're listening to your favorite music playlist, and you decide to keep listening as long as it's raining outside. You don't know exactly how long the rain will last, so you continue checking periodically. Once it stops raining, you'll stop the music and go outside. In programming, similar indefinite scenarios occur, like waiting for user input, processing data until a certain condition is met, or running background tasks in a game as long as the game is active.

Syntax

The syntax of the while loop in JavaScript is straightforward:

Image
Javascript
Javascript
. . . .

Parameters

  • Condition: The loop will continue to execute the code block as long as this condition evaluates to true. Once the condition becomes false, the loop stops.

Execution Flow

The execution flow of the while loop is as shown in flow-chart below.

Image

Examples

Example 1: Counting Up

Let's start with a simple example where we count from 1 to 5 using a while loop.

Javascript
Javascript

. . . .

This loop will print the numbers 1 through 5 to the console, incrementing the count by 1 in each iteration until the count is greater than 5.

Example 2: Sum of Positive Numbers

For a simple use case that involves user input, consider a program that calculates the sum of positive numbers entered by the user. For the sake of this example, let's simulate user input with an array of numbers, stopping the summation when a negative number is encountered.

Javascript
Javascript

. . . .

This example starts with an array of numbers and initializes a sum variable at 0. It uses a while loop to iterate through the array, adding each number to the sum as long as the number is positive (i.e., greater than or equal to 0). The loop stops when it encounters a negative number or reaches the end of the array. Finally, it prints the sum of the positive numbers.

The while loop is a versatile tool in JavaScript that allows you to execute code repeatedly under flexible conditions. It's especially useful in situations where the number of iterations is not known in advance. By understanding how to use while loops effectively, you can handle a wide range of programming scenarios with ease.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next