0
0
Javascriptprogramming~5 mins

Why loops are needed in Javascript

Choose your learning style9 modes available
Introduction

Loops help us repeat actions many times without writing the same code again and again.

When you want to print numbers from 1 to 10.
When you need to check each item in a shopping list.
When you want to add up all scores in a game.
When you want to repeat a task until a condition is met.
Syntax
Javascript
for (let i = 0; i < count; i++) {
  // code to repeat
}

The for loop repeats code a set number of times.

You can also use while loops for repeating until a condition changes.

Examples
This prints numbers 1 to 5, one by one.
Javascript
for (let i = 1; i <= 5; i++) {
  console.log(i);
}
This counts down from 3 to 1 using a while loop.
Javascript
let count = 3;
while (count > 0) {
  console.log('Counting down:', count);
  count--;
}
Sample Program

This program says hello three times, showing the number each time.

Javascript
for (let i = 1; i <= 3; i++) {
  console.log(`Hello number ${i}`);
}
OutputSuccess
Important Notes

Loops save time and make code shorter and easier to read.

Be careful to avoid loops that never stop, called infinite loops.

Summary

Loops repeat actions without rewriting code.

They help work with many items or repeat tasks easily.

Use loops to make your programs smarter and faster.