JavaScript Loops — Complete Guide with Examples

JavaScript Loops — Complete Guide with Examples

JavaScript Loops — Complete Guide with Examples | TipsInLearning
JavaScript Lesson

JavaScript Loops

Master loops: learn how to use for, while, and do-while to repeat code efficiently. Control iteration with break and continue statements. Complete guide with real-world examples.

18 min read
Beginner
Control Flow
Free Course
What You'll Learn in This Lesson
for, while, and do-while loops
Loop control with break and continue
for...in and for...of loops
When to use each loop type
Iterating arrays and objects
Real-world loop examples

What are JavaScript Loops?

Loops allow you to repeat code multiple times without rewriting it. They're essential for processing data, iterating through arrays, and automating repetitive tasks. JavaScript provides several types of loops, each suited for different scenarios.

Why use loops?

Less Code
Repeat actions without rewriting code
More Efficient
Process large amounts of data quickly
Flexible
Multiple loop types for different needs

The for Loop

The for loop is used to repeat code a specific number of times. It's the most common loop and works great when you know exactly how many iterations you need.

Syntax & Structure

JavaScript — for Loop
for (initialization; condition; increment) {
    // code to be executed
}
PartPurposeExample
initializationSets starting valuelet i = 0
conditionChecked before each iterationi < 5
incrementExecuted after each iterationi++

Basic Examples

JavaScript — for Loop Examples
// Loop 5 times
for (let i = 0; i < 5; i++) {
    // Runs with i: 0, 1, 2, 3, 4
}

// Count down
for (let i = 10; i >= 1; i--) {
    // Counts from 10 down to 1
}

Iterating Over Arrays

JavaScript — Array Iteration
let fruits = ["Apple", "Banana", "Orange"];

for (let i = 0; i < fruits.length; i++) {
    // fruits[0], fruits[1], fruits[2]
}
Pro Tip: Use array.length to get the number of elements. This works automatically even if the array grows or shrinks.

The while Loop

The while loop repeats code as long as a condition is true. Use it when you don't know exactly how many iterations you need.

Syntax

JavaScript — while Loop
while (condition) {
    // code to be executed
    // Must change condition to avoid infinite loop!
}

Examples

JavaScript — while Loop Examples
let i = 0; while (i < 5) { // Runs 5 times i++; } // User input example let input = ""; while (input !== "quit") { input = prompt("Type 'quit' to exit:"); }
Warning: Be careful not to create infinite loops! Always ensure the condition will eventually become false.

The do-while Loop

The do-while loop is like while, but it executes the code block at least once before checking the condition.

Syntax

JavaScript — do-while Loop
do {
    // code to be executed
} while (condition);

Examples

JavaScript — do-while Examples
let i = 0;
do {
    // Runs at least once
    i++;
} while (i < 5);

// Menu system
let choice = "";
do {
    choice = prompt("1: Start  2: Settings  3: Exit");
} while (choice !== "3");
Use do-while for: Menu systems, user input validation, and cases where you need to run code at least once.

break & continue Statements

Control loop execution flow with break (exit immediately) and continue (skip to next iteration).

break Statement

Terminates the loop immediately and jumps to code after the loop.

JavaScript — break Statement
for (let i = 0; i < 10; i++) { if (i === 5) { break; // Exits loop immediately } // Runs for i: 0, 1, 2, 3, 4 }

continue Statement

Skips the current iteration and moves to the next one.

JavaScript — continue Statement
for (let i = 0; i < 5; i++) { if (i === 2) { continue; // Skips this iteration } // Runs for i: 0, 1, 3, 4 (skips 2) }

Comparison: break vs continue

StatementEffectWhen to Use
breakExit loop immediatelyWhen you found what you need
continueSkip current iterationWhen you want to ignore certain items

The for...in Loop

The for...in loop iterates over object properties and array indices. Perfect for objects with named properties.

Syntax

JavaScript — for...in Loop
for (key in object) {
    // code to be executed
}

Examples

JavaScript — for...in Examples
let person = { name: "John", age: 30, city: "New York" }; for (let key in person) { // key: "name", "age", "city" // person[key]: "John", 30, "New York" } // With arrays (not ideal) let fruits = ["Apple", "Banana"]; for (let index in fruits) { // index: "0", "1" (as strings!) }
Note: for...in returns indices as strings for arrays. Use for...of for arrays instead.

The for...of Loop

The for...of loop iterates over values of iterables (arrays, strings). It's cleaner than for...in for arrays and strings.

Syntax

JavaScript — for...of Loop
for (value of iterable) {
    // code to be executed
}

Examples

JavaScript — for...of Examples
let fruits = ["Apple", "Banana", "Orange"];

for (let fruit of fruits) {
    // fruit: "Apple", "Banana", "Orange"
}

// With strings
let text = "Hello";
for (let char of text) {
    // char: "H", "e", "l", "l", "o"
}

Loop Type Comparison

TypeBest ForReturnsExample
forKnown iterationsIndexfor (let i = 0; i < 5; i++)
whileUnknown iterationsN/Awhile (condition)
do-whileAt least onceN/Ado { } while (condition)
for...inObject keysKeyfor (let key in obj)
for...ofArray valuesValuefor (let val of arr)

Best Practices

1
Choose the right loop type
Use for arrays, while for conditions, do-while for at-least-once
2
Avoid infinite loops
Always ensure conditions change and will eventually become false
3
Use meaningful variable names
Use 'fruit', 'user' instead of just 'i', 'j', 'k'
4
Keep loops simple and readable
Extract complex logic into separate functions
5
Consider array methods
forEach, map, filter are often better than loops
Modern JavaScript: Array methods like forEach(), map(), and filter() are often more readable and handle edge cases better than traditional loops.
Lesson Summary — Key Takeaways
1for loops are best for known iterations and arrays
2while loops continue until a condition becomes false
3do-while loops execute at least once before checking
4break exits a loop, continue skips to next iteration
5for...of loops values, for...in loops keys/indices
6Always avoid infinite loops by ensuring conditions change

Frequently Asked Questions

Common questions about JavaScript loops:

Loops allow you to repeat code multiple times without rewriting it. They're essential for processing arrays, iterating through data, and automating repetitive tasks in JavaScript.

A while loop checks the condition first, so it might not run at all. A do-while loop executes the code at least once before checking the condition. Use do-while for menus or input validation.

Use a for loop when you know exactly how many times you need to repeat code. It's perfect for iterating through arrays with a known length and counting up or down.

The break statement immediately exits the loop without executing remaining iterations. It's useful when you find what you're looking for and don't need to continue searching.

The continue statement skips the current iteration and moves to the next one. It's useful for ignoring certain items while processing the rest of your data.

Use for...of for arrays because it gives you the actual values directly. for...in returns indices as strings and isn't designed for arrays. However, for...in is great for objects.

Post a Comment