JavaScript Loops
Learn how to repeat code efficiently using for, while, do...while, for...of, for...in loops, nested loops, break, continue, and practical looping patterns.
Introduction
Programs frequently need to perform the same action more than once. Writing the same code repeatedly would make programs long, difficult to maintain, and inefficient.
Imagine displaying the numbers from 1 to 100. Writing one hundred separate console.log() statements would technically work, but it would be repetitive and impractical.
JavaScript solves this problem with loops. A loop repeats a block of code while a condition remains true or while values are available to process.
Loops are essential for processing collections of data, creating patterns, repeating calculations, validating input, searching values, generating user interfaces, and automating repetitive tasks.
- What loops are and why they are needed.
- How loop execution works.
- The meaning of initialization, condition, iteration, and update.
- How the for loop works.
- How to count forward and backward.
- How to use custom step values.
- How to generate even and odd numbers.
- How to create multiplication tables.
- How to calculate sums and factorials.
- How the while loop works.
- When to use a while loop.
- How the do...while loop works.
- The difference between while and do...while.
- What infinite loops are.
- How the break statement works.
- How the continue statement works.
- The difference between break and continue.
- How nested loops work.
- How to create patterns using nested loops.
- How to loop through strings.
- How the for...of loop works.
- How the for...in loop works.
- The difference between for...of and for...in.
- How to loop through arrays.
- How to search and analyze values.
- How to choose the correct loop.
- How loops are used in real applications.
What is a Loop?
A loop is a programming structure that repeatedly executes a block of code until a condition becomes false or until there are no more values to process.
START
│
▼
Check Condition
│
├── true ──► Execute Code
│ │
│ ▼
│ Update Value
│ │
└─────────────────┘
│
└── false ──► STOPconsole.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);for (let number = 1; number <= 5; number++) {
console.log(number);
}- A loop repeats code.
- Each repetition is called an iteration.
- A condition usually controls when repetition stops.
- Loops reduce duplicate code.
Why Do We Need Loops?
Loops allow developers to automate repetitive operations. Instead of writing the same instructions many times, we write the instructions once and define how many times they should execute.
Repeating Calculations
Perform calculations for many numbers without repeating code manually.
Processing Lists
Process products, users, messages, scores, and other collections of data.
Searching Data
Check values one by one until the required information is found.
Game Logic
Update players, enemies, objects, scores, and game states repeatedly.
User Interfaces
Generate repeated elements such as cards, menu items, rows, and options.
Automation
Repeat tasks efficiently without writing duplicate instructions.
Real-World Analogy
Imagine a teacher checking examination papers. The teacher repeats the same basic process for every paper until all papers have been checked.
Start with First Paper
│
▼
Check Paper
│
▼
Record Marks
│
▼
Are More Papers Available?
│
┌────┴────┐
│ │
Yes No
│ │
▼ ▼
Next Paper Finish
│
└─────────► RepeatA programming loop works in a similar way. It performs an action, moves to the next iteration, checks whether repetition should continue, and eventually stops.
How Loops Work
Most loops follow four basic steps: initialize a control value, check a condition, execute code, and update the control value.
1. INITIALIZE
│
▼
2. CHECK CONDITION
│
┌───┴───┐
│ │
true false
│ │
▼ ▼
3. EXECUTE STOP
│
▼
4. UPDATE
│
└────────► Return to Conditionfor (let count = 1; count <= 3; count++) {
console.log('Iteration:', count);
}Loop Terminology
Understanding common loop terminology makes it easier to understand every type of JavaScript loop.
Term Meaning
--------------------------------------------------
Initialization Creates the starting value
Condition Decides whether the loop continues
Iteration One complete repetition
Loop Body Code executed during each iteration
Update Changes the control value
Counter Variable that tracks repetitions
Termination The point where the loop stopsfor (
let i = 1; // Initialization
i <= 5; // Condition
i++ // Update
) {
// Loop Body
console.log(i);
}Types of Loops
JavaScript provides several loop structures. Each one is useful for different situations.
for Loop
Best when the number of repetitions is known or controlled by a counter.
while Loop
Best when repetition depends primarily on a condition.
do...while Loop
Executes the code at least once before checking the condition.
for...of Loop
Loops through values in iterable collections such as arrays and strings.
for...in Loop
Loops through enumerable property keys of an object.
The for Loop
The for loop is commonly used when the number of repetitions is known or when a counter controls the loop.
for (let i = 1; i <= 5; i++) {
console.log(i);
}for Loop Syntax
for (initialization; condition; update) {
// Code to repeat
}for (let i = 1; i <= 5; i++)
└────┬────┘ └──┬──┘ └─┬─┘
│ │ │
│ │ └── Update
│ │
│ └────────── Condition
│
└────────────────────── InitializationInitialization
The initialization runs once before the loop begins. It usually creates the loop counter.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// let i = 1 runs only once- Runs once before the first iteration.
- Usually creates a counter variable.
- Common names include i, j, index, and count.
- The starting value can be any appropriate number.
Condition
The condition is checked before every iteration. The loop continues while the condition is truthy.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// The loop continues while:
// i <= 5When i becomes 6, the condition i <= 5 becomes false and the loop stops.
Update Expression
The update expression runs after every completed iteration. It usually changes the counter.
for (let i = 1; i <= 5; i++) {
console.log(i);
}for (let i = 5; i >= 1; i--) {
console.log(i);
}for (let i = 0; i <= 10; i += 2) {
console.log(i);
}for Loop Execution Flow
INITIALIZATION
│
▼
CHECK CONDITION
│
┌────┴────┐
│ │
true false
│ │
▼ ▼
EXECUTE BODY STOP
│
▼
UPDATE
│
└──────────► CHECK CONDITIONfor (let i = 1; i <= 3; i++) {
console.log('Value:', i);
}Initialize: i = 1
Check: 1 <= 3 → true
Print: Value: 1
Update: i becomes 2
Check: 2 <= 3 → true
Print: Value: 2
Update: i becomes 3
Check: 3 <= 3 → true
Print: Value: 3
Update: i becomes 4
Check: 4 <= 3 → false
STOPCounting Forward
for (let i = 1; i <= 10; i++) {
console.log(i);
}Counting Backward
for (let i = 5; i >= 1; i--) {
console.log(i);
}
console.log('Go!');Custom Step Values
A loop counter does not need to increase or decrease by one. The update expression can use any suitable step value.
for (let i = 0; i <= 25; i += 5) {
console.log(i);
}for (let i = 50; i >= 0; i -= 10) {
console.log(i);
}Even Numbers
for (let number = 2; number <= 20; number += 2) {
console.log(number);
}for (let number = 1; number <= 10; number++) {
if (number % 2 === 0) {
console.log(number);
}
}Odd Numbers
for (let number = 1; number <= 19; number += 2) {
console.log(number);
}Multiplication Table
const number = 5;
for (let i = 1; i <= 10; i++) {
console.log(
`${number} × ${i} = ${number * i}`
);
}Sum of Numbers
A variable can store an accumulated result while a loop processes multiple values.
let sum = 0;
for (let number = 1; number <= 5; number++) {
sum += number;
}
console.log('Total:', sum);Start: sum = 0
Add 1 → sum = 1
Add 2 → sum = 3
Add 3 → sum = 6
Add 4 → sum = 10
Add 5 → sum = 15Factorial
The factorial of a positive integer is the product of that number and every positive integer below it.
5! = 5 × 4 × 3 × 2 × 1
5! = 120const number = 5;
let factorial = 1;
for (let i = 1; i <= number; i++) {
factorial *= i;
}
console.log(
`${number}! = ${factorial}`
);The while Loop
The while loop repeats a block of code while a condition remains truthy. It is useful when the number of repetitions is not known in advance.
while (condition) {
// Code to repeat
}let count = 1;
while (count <= 5) {
console.log(count);
count++;
}while Loop Flow
CHECK CONDITION
│
┌────┴────┐
│ │
true false
│ │
▼ ▼
EXECUTE BODY STOP
│
▼
UPDATE VALUE
│
└──────────► CHECK CONDITIONBecause the condition is checked before the loop body, a while loop may execute zero times.
let number = 10;
while (number < 5) {
console.log(number);
number++;
}
console.log('Finished');When to Use while
A while loop is useful when repetition depends on a changing condition and the exact number of iterations is not known beforehand.
let balance = 1000;
while (balance < 5000) {
balance += 1000;
console.log('Balance:', balance);
}- The exact number of repetitions is unknown.
- Repetition depends mainly on a condition.
- The condition may change because of user input.
- The loop should continue until a state changes.
The do...while Loop
The do...while loop executes its body first and checks the condition afterward. Therefore, it always executes at least once.
do {
// Code executes first
} while (condition);let count = 1;
do {
console.log(count);
count++;
} while (count <= 5);let number = 10;
do {
console.log(number);
} while (number < 5);do...while Flow
EXECUTE BODY
│
▼
UPDATE VALUE
│
▼
CHECK CONDITION
│
┌────┴────┐
│ │
true false
│ │
│ ▼
│ STOP
│
└──────────► EXECUTE BODY- while checks before execution.
- do...while executes before checking.
- while may execute zero times.
- do...while always executes at least once.
while vs do...while
Feature while do...while
----------------------------------------------------
Condition checked Before body After body
Minimum executions 0 1
May skip completely Yes No
Semicolon at end No Yes
Best use Condition Must run once
first before checkingInfinite Loops
An infinite loop is a loop whose stopping condition never becomes false.
// ❌ Do not run this example
for (let i = 1; i > 0; i++) {
console.log(i);
}// ❌ Do not run this example
let count = 1;
while (count <= 5) {
console.log(count);
// count is never updated
}- An infinite loop may freeze the browser tab.
- Always verify that the loop can reach its stopping condition.
- Update the control variable correctly.
- Be careful with incorrect comparison operators.
- Test loops with small ranges while learning.
The break Statement
The break statement immediately stops the nearest loop, even when the normal loop condition is still true.
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}const numbers = [10, 20, 30, 40, 50];
const target = 30;
for (const number of numbers) {
if (number === target) {
console.log('Found:', number);
break;
}
console.log('Checking:', number);
}The continue Statement
The continue statement skips the remaining code in the current iteration and moves to the next iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}for (let number = 1; number <= 10; number++) {
if (number % 2 === 0) {
continue;
}
console.log(number);
}break vs continue
Statement Effect
--------------------------------------------
break Stops the entire loop
continue Skips only the current iteration
and continues with the next oneBREAK
1 → 2 → 3 → BREAK → LOOP ENDS
CONTINUE
1 → 2 → 3 → CONTINUE → 4 → 5Nested Loops
A loop placed inside another loop is called a nested loop. The inner loop completes all of its iterations for every single iteration of the outer loop.
for (let row = 1; row <= 3; row++) {
for (let column = 1; column <= 2; column++) {
console.log(
`Row ${row}, Column ${column}`
);
}
}Nested Loop Flow
Outer Loop: 1
│
├── Inner Loop: 1
├── Inner Loop: 2
└── Inner Loop: 3
Outer Loop: 2
│
├── Inner Loop: 1
├── Inner Loop: 2
└── Inner Loop: 3
Outer Loop: 3
│
├── Inner Loop: 1
├── Inner Loop: 2
└── Inner Loop: 3Pattern Example
for (let row = 1; row <= 5; row++) {
let pattern = '';
for (let column = 1; column <= row; column++) {
pattern += '* ';
}
console.log(pattern);
}Row 1 → 1 Star
Row 2 → 2 Stars
Row 3 → 3 Stars
Row 4 → 4 Stars
Row 5 → 5 StarsMultiplication Grid
for (let number = 1; number <= 3; number++) {
console.log(`Table of ${number}`);
for (let multiplier = 1; multiplier <= 5; multiplier++) {
console.log(
`${number} × ${multiplier} = ${number * multiplier}`
);
}
console.log('---');
}Looping Through Strings
A string contains characters at numbered positions. A traditional for loop can process each character using its index.
const word = 'JavaScript';
for (let index = 0; index < word.length; index++) {
console.log(
`Index ${index}: ${word[index]}`
);
}const text = 'JavaScript';
let vowelCount = 0;
for (let index = 0; index < text.length; index++) {
const character =
text[index].toLowerCase();
if (
character === 'a' ||
character === 'e' ||
character === 'i' ||
character === 'o' ||
character === 'u'
) {
vowelCount++;
}
}
console.log('Vowels:', vowelCount);The for...of Loop
The for...of loop processes values from iterable objects such as arrays and strings.
for (const value of iterable) {
// Use value
}const numbers = [10, 20, 30];
for (const number of numbers) {
console.log(number);
}for...of with Strings
const language = 'JavaScript';
for (const character of language) {
console.log(character);
}const word = 'Hello';
let reversed = '';
for (const character of word) {
reversed =
character + reversed;
}
console.log(reversed);for...of with Arrays
const fruits = [
'Apple',
'Mango',
'Orange'
];
for (const fruit of fruits) {
console.log(fruit);
}const prices = [100, 250, 75, 125];
let total = 0;
for (const price of prices) {
total += price;
}
console.log('Total:', total);The for...in Loop
The for...in loop iterates through enumerable property keys of an object.
for (const key in object) {
// Use key
}const user = {
name: 'Rahul',
age: 25,
city: 'Mumbai'
};
for (const key in user) {
console.log(key);
}for...in with Objects
const product = {
name: 'Laptop',
price: 75000,
brand: 'TechPro'
};
for (const key in product) {
console.log(
`${key}: ${product[key]}`
);
}- for...in gives property keys.
- Use object[key] to access the corresponding value.
- It is commonly used with objects.
- It should not normally be the first choice for array values.
for...of vs for...in
Feature for...of for...in
----------------------------------------------------
Returns Values Keys
Best for Arrays Objects
Strings
Array use Recommended Usually avoid
Object use Not directly Recommendedconst colors = ['Red', 'Green', 'Blue'];
for (const color of colors) {
console.log(color);
}const user = {
name: 'Amit',
age: 30
};
for (const key in user) {
console.log(key);
}Looping Through Arrays
Arrays are one of the most common data structures processed with loops. A traditional for loop provides access to both the index and the value.
const students = [
'Aarav',
'Priya',
'Rohan'
];
for (
let index = 0;
index < students.length;
index++
) {
console.log(
`${index + 1}. ${students[index]}`
);
}Finding a Value
const products = [
'Laptop',
'Mouse',
'Keyboard',
'Monitor'
];
const target = 'Keyboard';
let found = false;
for (const product of products) {
if (product === target) {
found = true;
break;
}
}
if (found) {
console.log('Product found.');
} else {
console.log('Product not found.');
}Finding Maximum Value
const numbers = [25, 80, 15, 120, 60];
let maximum = numbers[0];
for (const number of numbers) {
if (number > maximum) {
maximum = number;
}
}
console.log('Maximum:', maximum);Start maximum = 25
Compare 25 → maximum = 25
Compare 80 → maximum = 80
Compare 15 → maximum = 80
Compare 120 → maximum = 120
Compare 60 → maximum = 120Counting Matches
const scores = [
75,
30,
90,
45,
20,
60
];
let passedStudents = 0;
for (const score of scores) {
if (score >= 40) {
passedStudents++;
}
}
console.log(
'Passed Students:',
passedStudents
);User Input Loop
A loop can continue asking for input until the user provides an acceptable value.
let age;
do {
age = Number(
prompt('Enter an age greater than 0:')
);
} while (
Number.isNaN(age) ||
age <= 0
);
console.log('Valid age:', age);Complete Number Analyzer
The following example analyzes every number from 1 to a user-defined limit and counts even and odd values.
<div class="number-analyzer">
<h2>Number Analyzer</h2>
<input
type="number"
id="limit"
placeholder="Enter a positive number"
>
<button id="analyzeButton">
Analyze Numbers
</button>
<pre id="result"></pre>
</div>const limitInput =
document.getElementById('limit');
const analyzeButton =
document.getElementById('analyzeButton');
const result =
document.getElementById('result');
analyzeButton.addEventListener('click', function () {
const limit =
Number(limitInput.value);
if (
Number.isNaN(limit) ||
limit <= 0 ||
!Number.isInteger(limit)
) {
result.textContent =
'Please enter a positive whole number.';
return;
}
let evenCount = 0;
let oddCount = 0;
let output = '';
for (let number = 1; number <= limit; number++) {
if (number % 2 === 0) {
output += `${number} - Even\n`;
evenCount++;
} else {
output += `${number} - Odd\n`;
oddCount++;
}
}
output += '\n';
output += `Even Numbers: ${evenCount}\n`;
output += `Odd Numbers: ${oddCount}`;
result.textContent = output;
});Complete Multiplication Table Generator
<div class="table-generator">
<h2>Multiplication Table Generator</h2>
<input
type="number"
id="number"
placeholder="Enter a number"
>
<button id="generateButton">
Generate Table
</button>
<pre id="tableOutput"></pre>
</div>const numberInput =
document.getElementById('number');
const generateButton =
document.getElementById('generateButton');
const tableOutput =
document.getElementById('tableOutput');
generateButton.addEventListener('click', function () {
const number =
Number(numberInput.value);
if (Number.isNaN(number)) {
tableOutput.textContent =
'Please enter a valid number.';
return;
}
let output = '';
for (let multiplier = 1; multiplier <= 10; multiplier++) {
output +=
`${number} × ${multiplier} = ${number * multiplier}\n`;
}
tableOutput.textContent = output;
});Loop Execution Flow
┌──────────────────────┐
│ START LOOP │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ INITIALIZE │
│ │
│ Counter / State │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ CHECK CONDITION │
└──────────┬───────────┘
│
┌────┴────┐
│ │
false true
│ │
▼ ▼
STOP EXECUTE BODY
│
▼
Process Data
│
▼
break encountered?
│
┌────┴────┐
│ │
Yes No
│ │
▼ ▼
STOP continue?
│
┌────┴────┐
│ │
Yes No
│ │
└────┬────┘
▼
UPDATE STATE
│
└──────► CHECK CONDITIONChoosing the Right Loop
Situation Recommended Loop
--------------------------------------------------------
Known repetition count for
Counter-controlled repetition for
Unknown repetition count while
Condition-controlled repetition while
Must execute at least once do...while
Array values for...of
String characters for...of
Object property keys for...in
Need array index traditional for
Nested rows and columns nested loops- Use for when the repetition count is clear.
- Use while when the stopping condition is the main focus.
- Use do...while when the body must execute once before checking.
- Use for...of for values in arrays and strings.
- Use for...in for object property keys.
- Choose the loop that makes the intention easiest to understand.
Real-World Applications
Product Lists
Display and process products in online stores.
User Management
Process collections of users, permissions, and account information.
Data Analysis
Calculate totals, averages, maximum values, minimum values, and statistics.
Searching
Check values repeatedly until the required item is found.
Games
Process players, enemies, levels, objects, and repeated game actions.
Form Processing
Validate multiple fields and repeated user input.
DOM Elements
Process multiple HTML elements and update their content or styles.
API Data
Process collections of records returned by servers.
Common Beginner Mistakes
- Forgetting to update the loop counter.
- Creating an infinite loop accidentally.
- Using the wrong comparison operator.
- Using < when <= is required.
- Using <= when < is required.
- Starting the counter from the wrong value.
- Stopping the loop one iteration too early.
- Running the loop one iteration too many.
- Forgetting that array indexes start at 0.
- Using index <= array.length instead of index < array.length.
- Changing the wrong variable inside the loop.
- Resetting an accumulator inside the loop.
- Declaring a result variable in the wrong scope.
- Using break when continue is intended.
- Using continue when break is intended.
- Forgetting that break stops the entire nearest loop.
- Forgetting that continue skips only the current iteration.
- Using deeply nested loops unnecessarily.
- Creating expensive loops over very large data sets.
- Using for...in when array values are required.
- Expecting for...of to directly process plain object properties.
- Forgetting to access object values with object[key].
- Modifying a collection unexpectedly while iterating through it.
- Using a while loop without ensuring the condition can change.
- Forgetting the semicolon after do...while.
- Assuming a while loop always executes once.
- Assuming do...while checks before the first execution.
- Using complicated conditions that are difficult to understand.
- Not validating user input before using it as a loop limit.
- Allowing extremely large user-provided loop limits.
- Using duplicate code instead of a loop.
- Using a loop when a simpler direct operation would be clearer.
// ❌ Infinite loop: counter never changes
// let i = 1;
//
// while (i <= 5) {
// console.log(i);
// }
// ❌ Array index goes too far
// for (let i = 0; i <= items.length; i++) {
// console.log(items[i]);
// }
// ❌ Accumulator resets every iteration
// for (let i = 1; i <= 5; i++) {
// let total = 0;
// total += i;
// }
// ❌ Wrong loop for array values
// for (const index in colors) {
// console.log(index);
// }
// ❌ Missing semicolon
// do {
// console.log('Hello');
// } while (condition)Best Practices
- Choose the loop that best communicates the purpose.
- Use for loops for known repetition counts.
- Use while loops for condition-controlled repetition.
- Use do...while only when at least one execution is required.
- Use for...of for array and string values.
- Use for...in primarily for object property keys.
- Use descriptive counter names when possible.
- Short names such as i and j are acceptable for simple loops.
- Always ensure the stopping condition can eventually become false.
- Verify the starting value carefully.
- Verify the ending condition carefully.
- Check whether the boundary should use < or <=.
- Remember that array indexes begin at 0.
- Use index < array.length when iterating through every array element.
- Keep the loop body focused.
- Avoid deeply nested loops when simpler alternatives exist.
- Use break when the required result has already been found.
- Use continue to skip unwanted iterations.
- Do not overuse break and continue when normal conditions would be clearer.
- Declare accumulators before the loop.
- Update accumulators inside the loop.
- Use const for loop values that are not reassigned.
- Use let for counters and changing values.
- Avoid var in modern JavaScript loops.
- Validate user-provided loop limits.
- Avoid allowing extremely large uncontrolled repetition.
- Use template literals for readable loop output.
- Break complex loop conditions into descriptive variables.
- Test the first iteration.
- Test the last iteration.
- Test empty collections.
- Test single-value collections.
- Test boundary conditions.
- Add comments when the loop algorithm is not obvious.
- Prefer readability over clever loop tricks.
const scores = [75, 30, 90, 45, 20];
const passingScore = 40;
let passedStudents = 0;
let failedStudents = 0;
for (const score of scores) {
const hasPassed =
score >= passingScore;
if (hasPassed) {
passedStudents++;
} else {
failedStudents++;
}
}
console.log(
`Passed: ${passedStudents}`
);
console.log(
`Failed: ${failedStudents}`
);Frequently Asked Questions
What is a loop?
A loop repeatedly executes a block of code while a condition remains true or while values remain available to process.
What is an iteration?
One complete repetition of a loop is called an iteration.
Why are loops useful?
Loops automate repetitive tasks and reduce duplicate code.
What are the main JavaScript loops?
The main loop structures are for, while, do...while, for...of, and for...in.
When should I use a for loop?
Use a for loop when the number of repetitions is known or controlled by a counter.
What are the three main parts of a for loop?
Initialization, condition, and update expression.
How many times does initialization run?
The initialization section of a for loop runs once before the loop begins.
When is the for loop condition checked?
It is checked before every iteration.
When does the update expression run?
It runs after each completed iteration.
What does i++ mean?
It increases the value of i by one.
What does i-- mean?
It decreases the value of i by one.
Can a loop increase by more than one?
Yes. For example, i += 5 increases the counter by five.
When should I use a while loop?
Use while when repetition depends on a condition and the exact number of iterations is not known beforehand.
Can a while loop execute zero times?
Yes. Its condition is checked before the first execution.
What is a do...while loop?
It is a loop that executes its body before checking the condition.
How many times does do...while execute at minimum?
At least once.
What is the difference between while and do...while?
while checks before execution, while do...while checks after execution.
What is an infinite loop?
An infinite loop is a loop whose stopping condition never becomes false.
How can I prevent infinite loops?
Make sure the loop changes the values involved in its stopping condition.
What does break do?
break immediately stops the nearest loop.
What does continue do?
continue skips the rest of the current iteration and moves to the next one.
What is the difference between break and continue?
break stops the loop completely, while continue skips only one iteration.
What is a nested loop?
A nested loop is a loop placed inside another loop.
How does a nested loop execute?
The inner loop completes all of its iterations for each iteration of the outer loop.
What is for...of used for?
It is used to loop through values in iterable objects such as arrays and strings.
What is for...in used for?
It is used to loop through enumerable property keys of an object.
What is the difference between for...of and for...in?
for...of gives values, while for...in gives property keys.
Should I use for...in for arrays?
Usually no. for...of or a traditional for loop is generally more appropriate for arrays.
How do I access an object value inside for...in?
Use bracket notation such as object[key].
How do I loop through a string?
You can use a traditional for loop with indexes or use for...of to process characters directly.
How do I find a value in a loop?
Compare each value with the target and use break when the target is found.
How do I calculate a total using a loop?
Create an accumulator before the loop and add values to it during each iteration.
Why should an accumulator be declared outside the loop?
Declaring it inside the loop would reset it during every iteration.
Why do arrays usually use index < array.length?
The last valid array index is one less than the array length.
Can loops contain conditional statements?
Yes. Conditions are frequently used inside loops to filter, search, count, and control execution.
Can loops contain other loops?
Yes. These are called nested loops.
Which loop is best?
There is no single best loop. Choose the loop that most clearly expresses the required repetition.
Key Takeaways
- Loops repeat blocks of code.
- Each repetition is called an iteration.
- Loops reduce duplicate code.
- Most loops use a condition to determine when to stop.
- Initialization creates the starting state.
- The condition decides whether repetition continues.
- The update expression changes the loop state.
- The for loop is useful for counter-controlled repetition.
- A for loop contains initialization, condition, and update sections.
- Loops can count forward.
- Loops can count backward.
- Counters can use custom step values.
- Loops can generate even and odd numbers.
- Loops can generate multiplication tables.
- Accumulators can calculate totals.
- Loops can calculate factorials.
- The while loop repeats while a condition is truthy.
- A while loop may execute zero times.
- The do...while loop executes at least once.
- Infinite loops occur when the stopping condition never becomes false.
- break stops the nearest loop.
- continue skips the current iteration.
- Nested loops place one loop inside another.
- The inner loop completes for each outer loop iteration.
- Nested loops can create patterns and grids.
- Strings can be processed character by character.
- for...of processes iterable values.
- for...of is useful for arrays and strings.
- for...in processes object property keys.
- for...in is commonly used with objects.
- Traditional for loops provide direct index access.
- Loops can search for values.
- Loops can find maximum and minimum values.
- Loops can count matching values.
- Loops can repeatedly request user input.
- The correct loop depends on the problem.
- Readable loop logic is more important than clever code.
- Every loop should have a clear stopping condition.
Summary
Loops allow JavaScript programs to repeat actions efficiently. Instead of writing the same code many times, a loop defines the repeated action and controls when repetition should stop.
The for loop is useful when repetition is controlled by a counter or when the number of iterations is known. It combines initialization, condition checking, and updating in one structure.
The while loop is useful when repetition depends mainly on a condition. The do...while loop is similar, but it executes its body at least once before checking the condition.
The break statement stops a loop immediately, while continue skips the current iteration and moves to the next one.
Nested loops allow repeated operations inside other repeated operations. They are commonly used for patterns, tables, grids, and multi-dimensional data.
The for...of loop is designed for values in iterable collections such as arrays and strings, while the for...in loop is commonly used for object property keys.
Loops are used throughout real applications for processing data, searching values, calculating results, generating interfaces, validating input, and automating repetitive tasks.
- You understand what loops are.
- You understand why loops are needed.
- You understand loop execution flow.
- You understand loop terminology.
- You can use the for loop.
- You understand initialization.
- You understand loop conditions.
- You understand update expressions.
- You can count forward.
- You can count backward.
- You can use custom step values.
- You can generate even numbers.
- You can generate odd numbers.
- You can create multiplication tables.
- You can calculate sums.
- You can calculate factorials.
- You can use the while loop.
- You understand while loop execution.
- You know when to use while.
- You can use the do...while loop.
- You understand the difference between while and do...while.
- You understand infinite loops.
- You can use break.
- You can use continue.
- You understand the difference between break and continue.
- You can create nested loops.
- You can create patterns.
- You can process strings with loops.
- You can use for...of.
- You can use for...in.
- You understand the difference between for...of and for...in.
- You can loop through arrays.
- You can search for values.
- You can find maximum values.
- You can count matching values.
- You can process repeated user input.
- You can choose the appropriate loop.
- You are ready to learn JavaScript Functions.