DEV Community

antony stark
antony stark

Posted on

Looping statements in javascript

Looping statements in JavaScript are used to execute a block of code repeatedly as long as a specified condition is met, They help eliminate repetitive code, make programs efficient, and make it easy to traverse data structures like arrays or objects

standard for loop:-
Use this loop when you know exactly how many times you want the code to run.javascript// Syntax: for (initialization; condition; afterthought)
for (let i = 1; i <= 3; i++) {
console.log("Count:", i);
}
// Output:
// Count: 1
// Count: 2
// Count: 3
Use code with caution.Initialization: Runs once before the loop starts to set up a counter (let i = 1).Condition: Evaluated before every iteration; if true, the loop runs.Afterthought: Runs at the end of every loop iteration, usually to increment the counter (i++).

while loop:-
This loop repeats a code block as long as a specified condition remains true. Use it when you don't know the exact number of iterations beforehand.javascriptlet i = 1;
while (i <= 3) {
console.log("While Count:", i);
i++;
}

do while loop
A variant of the while loop, but with one major difference: it executes the code block once before checking the condition.javascriptlet i = 10;
do {
console.log("This runs exactly once!");
} while (i < 5);

Top comments (0)