Introduction to Loop
Learn how to repeat tasks efficiently in JavaScript using loops like for, while, and do...while.
What is a JavaScript Loop?Link to this section
A loop is a programming tool used to repeat a block of code multiple times until a specific condition is met. Instead of writing the same line of code over and over, a loop automates the repetition.
This loop prints numbers from 1 to 3.
- `for` is the **keyword** that starts the loop
- `let i = 1` is the **initialization** starting at 1
- `i <= 3` is the **condition** that keeps the loop running
- `i++` is the **increment** step that changes the counter
Loops are used whenever you need to perform repetitive actions without duplicating code.
Why Do We Need JavaScript Loops?Link to this section
Without loops, repeating tasks requires writing redundant code, which makes programs messy and hard to maintain.
- Displaying all items in an online shopping cart
- Printing student grades from a list of marks
- Sending automated notification emails to a group of users
- Calculating the total monthly expenses from daily records
- Loading rows of data from a database table onto a webpage
- Iterating through product prices to apply a discount
Using a loop to sum up an array of prices.
This code automatically processes every item in the array without needing separate addition statements for each price.
About JavaScript LoopsLink to this section
Loops work by checking a condition before or after each repetition. If the condition evaluates to true, the code block runs again. They are generally grouped into counter-controlled loops and condition-controlled loops.
| Loop Type | Best Used For | Condition Check |
|---|---|---|
| for | Known number of repetitions | Before execution |
| while | Unknown number of repetitions | Before execution |
| do...while | Running at least once | After execution |
A simple while loop execution.
Types of JavaScript LoopsLink to this section
1. The For LoopLink to this section
The for loop is the most common loop used when you know exactly how many times you want to run a block of code. It bundles initialization, condition, and increment into a single line.
Prints Day 1, Day 2, and Day 3.
Calculating total bill for items in a cart.
tip
2. The While LoopLink to this section
The while loop runs as long as a specified condition evaluates to true. It is ideal when you do not know beforehand how many times the loop will need to run.
Runs until energy drops to zero.
Doubles the target value until it reaches or exceeds 10.
warning
3. The Do...While LoopLink to this section
The do...while loop is similar to the while loop, but it guarantees that the code block will execute at least once before the condition is tested.
Executes the block once before checking attempts.
note
4. The For...Of LoopLink to this section
The for...of loop is a modern and clean way to iterate directly over the values of iterable objects like arrays or strings.
Prints each fruit in the array.
tip
5. The For...In LoopLink to this section
The for...in loop is used to iterate over the enumerable properties (keys) of an object.
Iterates over object keys and values.
warning
Break and Continue StatementsLink to this section
Break and continue statements allow you to control the flow of loops. Break exits the loop entirely, while continue skips the current iteration and moves to the next one.
Breaks out of the loop when i is 3.
Skips printing when i is 2.
tip
Complete Coding ExampleLink to this section
A complete script filtering passing student grades.
This complete example iterates through an array of scores, skips failing grades using continue, counts the passing students, and logs the final tally.
Important NotesLink to this section
- Loops automate repetitive execution of code blocks.
- A for loop is best when the number of iterations is known.
- A while loop checks its condition before running the block.
- A do...while loop always runs at least once.
- The for...of loop is ideal for iterating through arrays.
- The for...in loop is designed for iterating over object keys.
- Always ensure loop conditions eventually evaluate to false.
- Use break to exit a loop prematurely.
- Use continue to skip the rest of the current iteration.
- Infinite loops occur when the termination condition is never met.
SummaryLink to this section
Loops are foundational programming constructs that eliminate code duplication by automating repetitive tasks. By mastering for, while, and specialized collection loops, you can handle large sets of data, build dynamic applications, and write cleaner, more maintainable code.
Check Your UnderstandingLink to this section
Which loop is best when you know the exact number of iterations?
Practice ChallengesLink to this section
1. Print Numbers 1 to 5
Write a for loop that prints the numbers from 1 to 5 to the console.
Expected output
1
2
3
4
5Hint: Initialize a counter at 1 and loop while it is less than or equal to 5.
2. Sum Array Elements
Create an array of three numbers [5, 10, 15] and use a for loop to calculate and print their total sum.
Expected output
30Hint: Declare a total variable outside the loop and add each array element to it inside the loop.
3. Countdown Timer
Write a while loop that starts at 3 and counts down to 1, printing each number, and then prints 'Liftoff!'.
Expected output
3
2
1
Liftoff!Hint: Decrement the counter variable inside the loop body.
4. Even Numbers Filter
Use a for loop from 1 to 10, and use a continue statement to skip odd numbers, printing only even numbers.
Expected output
2
4
6
8
10Hint: Check if the number modulo 2 is not equal to 0, then call continue.
5. Find Maximum Price
Given an array of prices [12, 45, 23, 89, 34], write a loop to find and print the maximum price in the array.
Expected output
89Hint: Keep track of the highest number found so far in a variable and update it during iterations.
Rate this content
Sign in to rate
Discussion
Sign in to join the discussion