JavaScript Loop Statements
Loop statements are important control structures in programming languages, used to repeatedly execute a piece of code until a specific condition is met. In JavaScript, loop statements can help us efficiently process arrays, objects, and other data collections. Mastering loop statements is crucial for writing efficient JavaScript programs. In this chapter, we will learn in depth about various loop statements in JavaScript.
Basic Concepts of Loop Statements
Loop statements allow us to repeatedly execute code blocks, avoiding repetitive code. JavaScript provides several loop statements:
- for loop
- while loop
- do...while loop
- for...in loop
- for...of loop
for Loop
The for loop is one of the most commonly used loop statements, suitable for situations where the number of iterations is known.
Basic Syntax
for (initialization; condition; update) {
// Loop body
}Examples
// Print numbers 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Calculate the sum of 1 to 10
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
console.log("Sum of 1 to 10: " + sum); // 55Components of for Loop
- Initialization: Executed once before the loop starts
- Condition: Checked before each iteration, loop continues while true
- Update: Executed after each iteration
Reverse Loop
// Count down from 10 to 1
for (let i = 10; i >= 1; i--) {
console.log(i);
}Nested for Loops
// Print multiplication table
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
console.log(i + " × " + j + " = " + (i * j));
}
console.log("---");
}while Loop
The while loop repeatedly executes a code block while the condition is true.
Basic Syntax
while (condition) {
// Loop body
}Examples
// Print numbers 1 to 5
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
// Count the digits of a number
let number = 12345;
let count = 0;
let temp = number;
while (temp > 0) {
count++;
temp = Math.floor(temp / 10);
}
console.log(number + " has " + count + " digits");do...while Loop
The do...while loop executes the loop body at least once, then continues while the condition is true.
Basic Syntax
do {
// Loop body
} while (condition);Examples
// Execute at least once
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
// User input validation example
let userInput;
do {
userInput = prompt("Please enter 'yes' or 'no':");
} while (userInput !== "yes" && userInput !== "no");for...in Loop
The for...in loop is used to iterate over the enumerable properties of an object.
Basic Syntax
for (variable in object) {
// Loop body
}Examples
const person = {
name: "John",
age: 25,
city: "New York"
};
// Iterate over object properties
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Output:
// name: John
// age: 25
// city: New York
// Iterate over array (not recommended)
const colors = ["red", "green", "blue"];
for (let index in colors) {
console.log(index + ": " + colors[index]);
}
// Output:
// 0: red
// 1: green
// 2: bluefor...of Loop
The for...of loop is used to iterate over iterable objects (such as arrays, strings, Map, Set, etc.).
Basic Syntax
for (variable of iterable) {
// Loop body
}Examples
// Iterate over array
const fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
console.log(fruit);
}
// Output:
// apple
// banana
// orange
// Iterate over string
const message = "Hello";
for (let char of message) {
console.log(char);
}
// Output:
// H
// e
// l
// l
// o
// Iterate over Set
const uniqueNumbers = new Set([1, 2, 3, 4, 5]);
for (let num of uniqueNumbers) {
console.log(num);
}
// Iterate over Map
const userMap = new Map([
["name", "John"],
["age", 25],
["city", "New York"]
]);
for (let [key, value] of userMap) {
console.log(key + ": " + value);
}Loop Control Statements
break Statement
The break statement is used to immediately exit a loop.
// Find a specific element in an array
const numbers = [1, 3, 5, 7, 9, 11, 13];
let target = 7;
let found = false;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === target) {
console.log("Found " + target + " at position: " + i);
found = true;
break; // Exit loop immediately after finding
}
}
if (!found) {
console.log(target + " not found");
}continue Statement
The continue statement is used to skip the remaining part of the current iteration and proceed to the next iteration.
// Print even numbers from 1 to 10
for (let i = 1; i <= 10; i++) {
if (i % 2 !== 0) {
continue; // Skip odd numbers
}
console.log(i);
}
// Output: 2, 4, 6, 8, 10
// Process valid data in an array
const data = [1, null, 3, undefined, 5, 0, 7];
let sum = 0;
for (let value of data) {
if (value === null || value === undefined || value === 0) {
continue; // Skip invalid data
}
sum += value;
}
console.log("Sum of valid data: " + sum); // 16Label Statements
Label statements can be used with break and continue to control nested loops.
// Using label to break out of outer loop
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outer; // Break out of outer loop
}
console.log("i=" + i + ", j=" + j);
}
}
// Output:
// i=0, j=0
// i=0, j=1
// i=0, j=2
// i=1, j=0
// Using label to skip outer loop iteration
outer2: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
continue outer2; // Skip current iteration of outer loop
}
console.log("i=" + i + ", j=" + j);
}
}
// Output:
// i=0, j=0
// i=0, j=1
// i=0, j=2
// i=1, j=0
// i=2, j=0
// i=2, j=1
// i=2, j=2Performance Considerations for Loops
1. Cache Array Length
const arr = [1, 2, 3, 4, 5];
// Bad practice (calculates length each iteration)
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// Good practice (cache length)
for (let i = 0, len = arr.length; i < len; i++) {
console.log(arr[i]);
}2. Reverse Loop Optimization
const arr = [1, 2, 3, 4, 5];
// Reverse loop (avoids length comparison each time)
for (let i = arr.length - 1; i >= 0; i--) {
console.log(arr[i]);
}Use Cases for Different Loops
1. for Loop
Suitable for:
- Known number of iterations
- Need precise control over the loop process
- Array index operations
// Process array elements
for (let i = 0; i < array.length; i++) {
process(array[i], i);
}2. while Loop
Suitable for:
- Unknown number of iterations
- Condition-based loops
// Read data until end
let data = readData();
while (data !== null) {
processData(data);
data = readData();
}3. do...while Loop
Suitable for:
- Loops that must execute at least once
// User menu selection
let choice;
do {
choice = showMenu();
handleChoice(choice);
} while (choice !== "exit");4. for...in Loop
Suitable for:
- Iterating over object properties
// Iterate over object
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key + ": " + obj[key]);
}
}5. for...of Loop
Suitable for:
- Iterating over iterable objects
- Array iteration without needing index
// Iterate over array elements
for (let item of array) {
console.log(item);
}
// Iterate over string characters
for (let char of string) {
console.log(char);
}Best Practices for Loops
1. Choose the Right Loop Type
// Iterate over array elements - recommended to use for...of
const numbers = [1, 2, 3, 4, 5];
for (let num of numbers) {
console.log(num);
}
// Iterate over array elements with index - use for loop
for (let i = 0; i < numbers.length; i++) {
console.log(i + ": " + numbers[i]);
}
// Iterate over object properties - use for...in
const person = { name: "John", age: 25 };
for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(key + ": " + person[key]);
}
}2. Avoid Infinite Loops
// Ensure loop condition will change
let i = 0;
while (i < 10) {
console.log(i);
i++; // Must update loop variable
}
// Use break to prevent accidental infinite loops
let attempts = 0;
while (condition) {
// Execute operation
attempts++;
// Prevent infinite loop
if (attempts > 1000) {
console.log("Maximum attempts reached");
break;
}
}3. Use break and continue Wisely
// Data validation example
function processData(dataArray) {
for (let data of dataArray) {
// Skip invalid data
if (!isValid(data)) {
continue;
}
// Process data
let result = process(data);
// If processing fails, stop processing
if (!result.success) {
console.log("Processing failed, stopping");
break;
}
// Save result
saveResult(result);
}
}Practical Examples
Array Processing Utility Functions
// Array filter function
function filterArray(array, condition) {
const result = [];
for (let item of array) {
if (condition(item)) {
result.push(item);
}
}
return result;
}
// Array map function
function mapArray(array, transform) {
const result = [];
for (let i = 0; i < array.length; i++) {
result.push(transform(array[i], i));
}
return result;
}
// Array reduce function
function reduceArray(array, reducer, initialValue) {
let accumulator = initialValue;
for (let item of array) {
accumulator = reducer(accumulator, item);
}
return accumulator;
}
// Usage examples
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = filterArray(numbers, n => n % 2 === 0);
console.log("Even numbers:", evenNumbers); // [2, 4, 6, 8, 10]
const squares = mapArray(numbers, n => n * n);
console.log("Squares:", squares); // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
const sum = reduceArray(numbers, (acc, n) => acc + n, 0);
console.log("Sum:", sum); // 55Object Property Processing
// Object property transformation
function transformObject(obj, transformer) {
const result = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
const transformed = transformer(key, obj[key]);
result[transformed.key] = transformed.value;
}
}
return result;
}
// Object property filtering
function filterObject(obj, predicate) {
const result = {};
for (let key in obj) {
if (obj.hasOwnProperty(key) && predicate(key, obj[key])) {
result[key] = obj[key];
}
}
return result;
}
// Usage examples
const user = {
name: "John",
age: 25,
email: "john@example.com",
password: "secret123"
};
// Filter sensitive information
const publicInfo = filterObject(user, (key, value) => key !== "password");
console.log(publicInfo); // { name: "John", age: 25, email: "john@example.com" }
// Transform property names
const transformedUser = transformObject(user, (key, value) => ({
key: key.toUpperCase(),
value: typeof value === "string" ? value.toUpperCase() : value
}));
console.log(transformedUser);
// { NAME: "JOHN", AGE: 25, EMAIL: "JOHN@EXAMPLE.COM", PASSWORD: "SECRET123" }Loop Performance Test
// Performance test function
function performanceTest(testName, testFunction, iterations = 1000000) {
const startTime = performance.now();
for (let i = 0; i < iterations; i++) {
testFunction();
}
const endTime = performance.now();
console.log(testName + " took: " + (endTime - startTime) + " ms");
}
// Test performance of different loops
const testArray = new Array(10000).fill(0).map((_, i) => i);
// for loop
performanceTest("for loop", () => {
let sum = 0;
for (let i = 0; i < testArray.length; i++) {
sum += testArray[i];
}
});
// for...of loop
performanceTest("for...of loop", () => {
let sum = 0;
for (let value of testArray) {
sum += value;
}
});
// forEach loop
performanceTest("forEach loop", () => {
let sum = 0;
testArray.forEach(value => {
sum += value;
});
});Summary
Key points about JavaScript loop statements:
- for loop: Suitable for situations with known iteration count
- while loop: Suitable for situations with unknown iteration count
- do...while loop: Loop that executes at least once
- for...in loop: Iterate over object properties
- for...of loop: Iterate over iterable objects
- Loop control: break (exit loop), continue (skip current iteration)
- Label statements: Control nested loops
- Performance optimization: Cache length, choose appropriate loop type
- Best practices: Avoid infinite loops, use control statements wisely
Mastering loop statements is the foundation for writing efficient JavaScript programs. In the next chapter, we will learn about JavaScript functions.