JavaScript full playlist : • What is JavaScript? - #1 #JavaScript ...
The do...while loop in JavaScript is similar to the while loop, but with one key difference: the do...while loop will always execute its code block at least once, even if the condition is initially false. After the first iteration, it will continue executing as long as the specified condition remains true.
Here's the syntax of a do...while loop:
JavaScript code
do {
// code block to be executed
} while (condition);
Let's break down the components:
Code Block: The block of code enclosed in curly braces {} that will be executed at least once, regardless of the condition.
Condition: This is the expression that is evaluated after each iteration. If the condition evaluates to true, the loop will continue executing. If it evaluates to false, the loop will terminate.
Here are some examples:
Example 1: Simple do...while loop
JavaScript code
let i = 0;
do {
console.log(i);
i++;
} while (i less than 5);
In this example:
console.log(i); prints the value of i.
i++; increments i by 1 after each iteration.
The loop continues executing as long as i is less than 5.
Example 2: Using a do...while loop to process user input
JavaScript code:
let userInput;
do {
userInput = prompt("Enter a number greater than 10:");
if (userInput less than 10) {
console.log("Thank you!");
} else {
console.log("Please enter a number greater than 10.");
}
} while (userInput greater than equal to = 10);
In this example:
The loop continues to prompt the user for input until the entered number is greater than 10.
Example 3: Using a do...while loop to iterate over an array
JavaScript code:
const array = ['apple', 'banana', 'orange'];
let i = 0;
do {
console.log(array[i]);
i++;
} while (i less than array.length);
In this example, we're using a do...while loop to iterate over an array. The loop continues as long as i is less than the length of the array (array.length). Inside the loop, we access each element of the array using the loop counter i and then increment i after each iteration.
Chapter :
00:00 Do...While loop
00:30 Syntax
01:04 Example 1
01:21 Example 2
01:35 Example 3
01:56 Conclusion
Thank you for watching this video
Everyday Be Coding