Home Courses Loops - What is Loop & Types

Loops - What is Loop & Types

Loops are used to:

  1. Execute a block of code repeatedly
  2. Run code until a specific condition is met

Definition:

A loop allows you to automate repetitive tasks instead of writing the same code multiple times.


Why Do We Need Loops?

Without loops:


console.log(1);
console.log(2);
console.log(3);
// ...
console.log(10);

Problems:

  1. Time-consuming
  2. Repetitive code
  3. Higher chances of mistakes
  4. Not scalable (imagine printing up to 1000)

With Loops:


for (let i = 1; i <= 10; i++) {
console.log(i);
}

Benefits:

  1. Less code
  2. Faster execution
  3. Easy to manage and scale


Real-Life Example

Printing Table of 10

Without loop:


10 * 1
10 * 2
...
10 * 10

With loop:


for (let i = 1; i <= 10; i++) {
console.log(10 * i);
}


Types of Loops in JavaScript

for Loop

  1. Most commonly used loop
  2. Used when number of iterations is known


while Loop

  1. Runs while condition is true
  2. Used when iterations are not fixed


do...while Loop

  1. Runs at least once (even if condition is false)


for...of Loop

  1. Used for arrays and iterable data
  2. Gives values directly


for...in Loop

  1. Used for objects
  2. Iterates over keys


Key Concept

  1. Loops execute code automatically multiple times
  2. You only write code once
  3. Loop controls repetition using conditions


Share this lesson: