filmov
tv
While Loop in JavaScript -#10 @Everyday-Be-Coding

Показать описание
The while loop in JavaScript is another fundamental looping construct. It repeatedly executes a block of code as long as a specified condition evaluates to true. If the condition initially evaluates to false, the loop will not execute at all.
Here's the syntax of a while loop:
JavaScript code
while (condition) {
// code block to be executed
}
Let's break down the components:
Condition: This is the expression that is evaluated before each iteration. If the condition evaluates to true, the loop will execute. If it evaluates to false, the loop will terminate.
Code Block: The block of code enclosed in curly braces {} that will be executed repeatedly as long as the condition remains true.
Here are some examples:
Example 1: Simple while loop
JavaScript code
let i = 0;
while (i less than 5) {
i++;
}
In this example:
let i = 0; initializes the loop counter variable i to 0.
i less than 5; is the condition. As long as i is less than 5, the loop will continue executing.
i++; increments i by 1 after each iteration.
Example 2: Using a while loop to process user input
JavaScript Code:
let userInput;
while (true) {
userInput = prompt("Enter a number greater than 10:");
if (userInput greater than 10) {
break; // Exit the loop
} else {
}
}
In this example, the loop continues indefinitely (while (true)) until the user enters a number greater than 10. Once the condition is met (userInput greater than 10), the loop breaks using the break statement.
Example 3: Using a while loop to iterate over an array
JavaScript Code:
const array = ['apple', 'banana', 'orange'];
let i = 0;
i++;
}
Chapter :
00:00 While loop
00:24 Syntax
00:55 Example 1
01:14 Example 2
01:28 Example 3
01:50 Conclusion
Thank you for watching this video
EVERYDAY BE CODING