Briefly
Control structure that creates a loop.
How to write it
while (condition) { //body of the loop}
while (condition) { //body of the loop }
Example of printing the squares of numbers from an array:
const numbers = [1, 2, 3, 4, 5]let i = 0while (i < numbers.length) { const currentElement = numbers[i] console.log(currentElement * currentElement) i++}// prints 1, 4, 9, 16, 25let count = numbers.lengthwhile (count) { // option with typecasting in the loop condition console.log(count) count--}// prints 5, 4, 3, 2, 1
const numbers = [1, 2, 3, 4, 5] let i = 0 while (i < numbers.length) { const currentElement = numbers[i] console.log(currentElement * currentElement) i++ } // prints 1, 4, 9, 16, 25 let count = numbers.length while (count) { // option with typecasting in the loop condition console.log(count) count-- } // prints 5, 4, 3, 2, 1
In practice
Advice 1
🛠 Always use alternatives to the while
loop that are better suited for the task. For example, arrays have many convenient methods: for
, filter
, map
. They are more readable and contain less code.
🛠 Ensure that the condition changes with each execution of the loop body. If this does not happen, then the loop will most likely be infinite.
🛠 while
is a more flexible loop than for
, but it is easy to make a mistake when writing it. The moment of initialization and modification of variables in for
(initialization operation and step) is predefined. They can be violated, but it will not be easy to read. while
provides complete freedom to organize the loop as desired; it is completely manual control. It's easy to forget to write something — most often, the variable in the condition is forgotten to be changed in the loop body.