Skip to content
the poor coder

javascript while

Poor Man
Published
Reading time
1 min read

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:

Text

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:

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC