javascript while

Javascript While Loop

In JavaScript, a 'while' loop is a type of loop that allows a block of code to be executed repeatedly as long as the specified condition remains true.

The basic syntax of a 'while' loop is as follows:


while (condition) {
  // code block to be executed
}
  • The 'condition' is an expression that is evaluated before each iteration of the loop.
  • If the condition is true, the code block inside the loop will be executed.
  • If the condition is false, the loop will be exited and the program will continue with the next line of code.

Here's an example of how a 'while' loop can be used to iterate through an array:


const array = ['apple', 'banana', 'cherry'];
let i = 0;

while (i < array.length) {
  console.log(array[i]);
  i++;
}
  • In this example, the 'condition' is 'i < array.length'.
  • The code block inside the loop will be executed as long as 'i' is less than the length of the 'array'.
  • The variable 'i' is incremented by 1 after each iteration of the loop using the postfix increment operator (i++).

Another way to write this same code using a 'for' loop:


const array = ['apple', 'banana', 'cherry'];

for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

While loops and for loops are very similar, and you can use either one to achieve the same result. However, while loops are typically used when you don't know how many times you need to execute the loop beforehand, whereas for loops are typically used when you do know the number of iterations required.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe