DEV Community

G Gokul
G Gokul

Posted on

LOOPING IN JAVASCRIPT

Looping:

  • Loops in JavaScript are essential for executing a block of code repeatedly based on a specified condition.
  • They are powerful tools for automating tasks and streamlining your code.
  • JavaScript supports several types of loops, each suited for different scenarios.
  • Loops continue running until the condition becomes false.
  • They are useful for iterating over arrays, strings, and ranges of values.

Types of Loops:

1. for Loop:

  • The for loop is one of the most commonly used loops in JavaScript.
  • It provides a concise way of writing the loop structure by including initialization, condition, and increment/decrement in one line.

syntax:
for (initialization; condition; increment/decrement) {
// Code to execute}

Flowchart:

for loop

example:
for (let i = 0; i < 5; i++) {
console.log("Hello World!");
}

output:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

2. while Loop:

  • The while loop executes its statements as long as a specified condition evaluates to true.
  • It is useful when the number of iterations is not known beforehand.

syntax:
while (condition) {
// Code to execute
}

Flowchart:

while loop

example:
let i = 1;
let givenno = 54;
let count = 0;
while(i<=givenno){
if(givenno % i == 0){
count = count + 1;
}
i++;
}
console.log(count)

output:
8

3. do...while Loop:

  • The do-while loop is similar to the while loop, but it checks the condition after executing the statements.
  • This ensures that the loop executes at least once.

syntax:
do {
// Code to execute
} while (condition);

Flowchart:

do while

example:
let num = 1;
do {
console.log(num);
num++;
} while (num <= 5);

output:
1
2
3
4
5

4. for...of Loop:(TBD)
5. for...in Loop:(TBD)
6. Breaking & Skipping:(TBD)

References:

JavaScript Loops - GeeksforGeeks

Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.

favicon geeksforgeeks.org

Top comments (0)