JavaScript : While Loop

In JavaScript, the while loop is used to execute a block of code as long as a specified condition is true. It's a pre-test loop, meaning the condition is evaluated before the execution of the block. If the condition evaluates to true, the block of code is executed. Here's the syntax of the while loop:

Syntax:


while (condition) {
  // Code block to be executed
}

 

  • condition : An expression that is evaluated before each iteration. If the condition evaluates to true , the loop continues; if false, the loop terminates.

Example:


let count = 0;

while (count < 5) {
  console.log("Count: " + count);
  count++;
}

 

Output:


Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

 

Notes:

 

  • Make sure to include an update statement inside the loop to avoid infinite loops. Without an update statement, the loop will continue indefinitely.
  • If the condition evaluates to false initially, the code inside the loop will not execute at all.
  • You can use the while loop when you don't know in advance how many times the loop needs to be executed, and the number of iterations depends on a condition.

Example with User Input:


let userInput;
let sum = 0;

while (userInput !== 'exit') {
  userInput = prompt("Enter a number (type 'exit' to stop):");

  if (userInput !== 'exit' && !isNaN(userInput)) {
    sum += parseFloat(userInput);
  }
}

console.log("Sum of numbers entered: " + sum);
 

In this example, the loop continues prompting the user for numbers until they type exit. It then calculates the sum of the entered numbers.

AI car modification · buy quality backlinks · guest post service · link building service · link building service · buy backlinks · SEO, GEO, AEO, AIO and LLMO · Bedeutung von Backlinks für Google · winandoffice · aiswapface photo face swap · dofollow backlinks · link building service · guest post service · quality backlinks · guest post service · dofollow backlinks · link building service · dofollow backlinks · buy backlinks · buy quality backlinks · dofollow backlinks · dofollow backlinks · link building service · hacklink satın al · Contextual backlinks: judge the paragraph and destination together · hacklink · hacklink satın al · hacklink panel satın al · jojobet · hacklink satın al · jojobet · jojobet · jojobet · jojobet · jojobet · jojobet · jojobet · jojobet · jojobet · jojobet · jojobet giriş · jojobet güncel · jojobet · jojobet · jojobet · jojobet