In JavaScript, the while loop establishes a repetitive structure that runs as long as a designated condition holds true. This loop will persist in executing until the condition evaluates to false.
Within a while loop, the condition is defined prior to the execution of the loop. Typically, a variable is modified or incremented within the body of the while loop, which helps in deciding when the loop should terminate.
Syntax of JavaScript while Loop
The syntax of while loops is as follows:
while(condition){
//code block to be executed
}
Explanation:
while: This keyword is employed to commence a while loop.
Condition: Inside the while loop, the condition specified is a boolean expression that evaluates to either true or false. When the condition within the while loop evaluates to true, the loop's body executes. Conversely, when the expression is evaluated as false, the loop ceases its execution.
code block: The statements represent the instructions executed by the program as long as the specified condition remains valid.
Example
Let's see an example of it.
Code:
Example
let count = 1;
while (count<=5) {
console.log( "count: " + count) ;
count++
};
console.log("Loop completed");
Output:
count: 1
count: 2
count: 3
count: 4
count: 5
Loop completed
Explanation :
In the preceding illustration, we established a variable referred to as count utilizing the let keyword. We set the value of the variable count to 1. A while loop was employed in this scenario. The condition while (count<=5) executes repeatedly as long as the condition remains true. Once the condition evaluates to false, the loop concludes and displays the message "Loop Completed."
Flowchart
This flowchart illustrates how the while loop operates in JavaScript. You can see the progression of control within the while loop.
Examples of a while loop
Let’s examine a few examples to gain a better understanding of while loops. The examples are presented below:
Example 1:
In the following example, we initiate a variable called a utilizing the let keyword. We will display the message Welcome to our tutorial by employing a while loop.
Example
let a = 0;
while(a < 3){
console.log("Welcome to our tutorial");
a++;
}
Output:
Welcome to our tutorial
Welcome to our tutorial
Welcome to our tutorial
Example 2:
In the following example, we have declared a variable called arr using the let keyword. We will utilize a while loop to output numbers up to 4.
Example
let arr = [1, 2, 3, 4];
let i = 0;
while (i < arr.length) {
console.log(arr[i]);
i++;
}
Output:
1
2
3
4
Example 3:
In the following illustration, we will calculate the factorial of a number utilizing a while loop.
Example
let n=10, i=1, fact=1
while(i<=n)
{
fact = fact*i
i++
}
console.log("The factorial of a number is", fact)
Output:
The factorial of a number is 3628800
When to use the while loop in JavaScript?
In JavaScript, while loops are particularly useful when the termination condition is not predetermined.
Continuous Execution
JavaScript while loops are perfect for scenarios that necessitate ongoing evaluation and execution until a specific condition is modified.
Processing Items
While loops in JavaScript prove to be advantageous for handling items within an array, especially in scenarios where the operations performed may alter the length of the array.
Nested while loop
In JavaScript, a nested while loop is defined as a while loop that exists within another while loop. The outer loop runs initially, and during each iteration of this outer loop, the inner loop runs in its entirety.
Syntax
The syntax of a nested while loop is as follows:
while (outerCondition) {
// Code to be executed in the outer loop
while (innerCondition) {
// Code to be executed in the inner loop
}
}
Explanation:
while (outerCondition): Initially, this condition undergoes evaluation. If it evaluates to true, the code block associated with outerCondition will be executed. Conversely, if it evaluates to false, the entire nested loop will be bypassed.
while (innerCondition): When the innerCondition evaluates to true, the statements within the inner loop will continue to execute repeatedly as long as the condition remains true.
Example
In the following example, we will develop a program that displays the multiplication table by employing a while loop.
Example
let i = 1;
while (i<=10) {
let row = "";
let j = 1;
while (j<=10) {
row += (i * j) + "\t";
j++;
}
console.log(row);
i++
}
Output:
JavaScript Pyramid Programs using a while Loop
Example 1:
We have developed an uncomplicated program that utilizes a while loop to display a pyramid, as illustrated in the following example.
Example
let rows = 5;
let i = 1;
while (i <= rows) {
let str = ' '.repeat(rows - i) + '*'.repeat(2 * i - 1);
console.log(str);
i++;
}
Output:
Explanation:
In the code presented above, the variable rows is established to represent the height of the pyramid. The while loop iterates with i starting at 1 and continuing up to the value of rows, ensuring that the appropriate number of rows is created. The expression ' '.repeat(rows - i) adds spaces to align the stars in the center, and the method ''.repeat(2 i - 1) produces the stars necessary to shape the pyramid. The increment i++ increases the count of the current row.
Example 2:
In this example, we will demonstrate how to generate a pyramid shape using a while loop in JavaScript.
Example
let rows = 5;
let i = rows;
while (i >= 1) {
let str = ' '.repeat(rows - i) + '*'.repeat(2 * i - 1);
console.log(str);
i--;
}
Output:
Explanation:
In the code presented above, the variable "rows" specifies the height of the inverted pyramid. The while loop initiates with the value of "rows" and decreases "i" until it reaches 1. The expression ' '.repeat(rows-i) generates the necessary spaces for proper alignment, while ''.repeat(2 i - 1) outputs the appropriate number of asterisks for each row. The operation i-- reduces the count of rows, resulting in the pyramid becoming progressively smaller.
Features of the while loop in JavaScript
JavaScript's while loop possesses several key characteristics:
Condition-based execution
The loop persists in executing as long as the condition remains true. The evaluation of the condition occurs prior to each iteration, and if the condition is false from the outset, the entire loop body will be bypassed.
Flexibility
The while loop is ideal for scenarios in which the total number of iterations cannot be determined beforehand, as it relies on a specific condition being satisfied.
Control flow statements
In JavaScript, the break and continue statements serve as tools within a while loop to modify its flow of execution. The break statement causes the loop to end before it naturally concludes, whereas the continue statement bypasses the current iteration and advances to the subsequent one.
Nesting
While loops have the capability to be embedded within other while loops or various other loop types, facilitating the creation of more intricate control flow structures.
Conclusion:
The JavaScript while loop stands out as one of the most commonly utilized conditional loops. It is advisable to employ a while loop when the total number of iterations is unknown. In this article, we have explored all aspects of while loops and provided illustrative examples. The content covers topics such as the definition of a while loop, its practical applications, and various examples. This article is valuable for individuals at all skill levels, from novices to seasoned developers.
FAQs:
- What exactly is a while loop in JavaScript?
A while loop in JavaScript serves the purpose of executing a specific block of code repeatedly until a particular condition becomes true. Typically, we utilize a while loop in scenarios where the number of iterations is uncertain and relies on a certain condition being satisfied.
- What is the syntax for declaring a while loop in JavaScript?
The structure of the while loop in JavaScript is defined as:
While (condition)
{
// define the code here, which will be executed until the condition is true
}
- What exactly constitutes an infinite loop, and in what manner can it manifest within the context of a while loop?
An infinite loop occurs when a while loop continuously evaluates its condition as true, resulting in perpetual execution. This situation arises when the condition specified in the while statement fails to become false, and there is no code within the loop's body to modify the condition or facilitate an exit from the loop.
- Can a while loop be nested inside another while loop in JavaScript?
Indeed, it is possible to embed one while loop within another while loop in JavaScript.