๐จ๐ป๐ฑ๐ฒ๐ฟ๐ฆ๐ง๐ฎ๐ป๐ฑ๐ถ๐ป๐ด ๐ช๐ต๐ถ๐น๐ฒ ๐๐ผ๐ผ๐ฝ๐ฆ ๐๐ป ๐๐ฎ๐๐ฎ๐๐ฐ๐ฟ๐ถ๐ฝ๐ You use loops to repeat a set of instructions. Loops keep running until a condition is no longer true. They help you work with arrays, strings, and ranges of values.
Here are the types of loops in JavaScript:
- for loop
- while loop The while loop syntax is: while (condition) { // code to run }
Here's an example: let count = 1; while (count <= 5) { console.log(count); count++ } This will print numbers 1 to 5.
Another example: let i = 1; while (i < 4) { console.log(i); i++ } This will print numbers 1 to 3.
You can also use while loops to do simple math.
let total = 0;
let i = 1;
while (i <= 5) {
total = total + i;
i = i + 1;
}
console.log(total) will print 15.
Be careful not to create infinite loops. For example: let count = 1; while (count <= 5) { console.log(count); } This will run forever because count never changes.
Source: https://www.geeksforgeeks.org/javascript/loops-in-javascript/ Optional learning community: https://dev.to/ezhil_abinayak_e38eec8fb/understanding-while-loops-in-javascript-4hgm