Home >Web Front-end >CSS Tutorial >All About JavaScript Loops

All About JavaScript Loops

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2025-03-08 09:51:11462browse

All About JavaScript Loops

Every programming language utilizes loops to repeatedly execute a block of code. Loops are essential for processing arrays, lists, or repeating actions until a specific condition is met.

JavaScript offers a variety of loop types. This overview explores each type, highlighting their applications and comparative advantages.

while and do...while Loops

The while loop, the most fundamental loop, executes a block of code as long as a specified condition remains true. It's simple, readable, and often efficient. However, it's also prone to infinite loops if the condition isn't carefully managed. The do...while loop is similar, but the condition is checked after each iteration, guaranteeing at least one execution.

// Process an array until it's empty
let queue1 = ["a", "b", "c"];

while (queue1.length) {
  let item = queue1.shift();
  console.log(item);
}

// Similar, but handles empty array gracefully
let queue2 = [];

do {
  let item = queue2.shift() ?? "empty";
  console.log(item);
} while (queue2.length);

The for Loop

The for loop is ideal for iterating a specific number of times. It's powerful and efficient for repetitive tasks. While initially daunting to beginners, understanding its structure simplifies its use.

// Log numbers 1 to 5
for (let i = 1; i <= 5; i++) {
  console.log(i);
}

for...of and for await...of Loops

The for...of loop provides a concise way to iterate over iterable objects like arrays, maps, sets, and strings. It simplifies array traversal compared to traditional for loops.

let myList = ["a", "b", "c"];

for (let item of myList) {
  console.log(item);
}

for...of isn't limited to built-in iterables; custom iterables can be created by implementing the iterable protocol (adding a [Symbol.iterator] method). for await...of is the asynchronous counterpart, ideal for working with asynchronous iterables and generators.

async function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function* aNumberAMinute() {
  let i = 0;
  while (true) {
    yield i++;
    await delay(60000);
  }
}

for await (let i of aNumberAMinute()) {
  console.log(i);
  if (i >= 59) break;
}

Note: for await...of works with non-async iterables, but the reverse isn't true.

forEach and map Methods

forEach and map aren't strictly loops, but they facilitate array iteration. forEach executes a provided function once for each array element. While historically slower than for loops, modern JavaScript engines have minimized this performance difference. map creates a new array by applying a function to each element of the original array. Both methods offer readability advantages in certain contexts, particularly when working with functional programming paradigms.

["a", "b", "c"].forEach((item, index) => console.log(`${index}: ${item}`));

let doubled = [1, 2, 3].map(x => x * 2); // doubled = [2, 4, 6]

for...in Loop

The for...in loop iterates over the enumerable properties of an object. It also includes inherited properties, which can be a source of unexpected behavior. It's best suited for iterating over object literals where inherited properties aren't a concern. Key order is now consistent across browsers.

// Process an array until it's empty
let queue1 = ["a", "b", "c"];

while (queue1.length) {
  let item = queue1.shift();
  console.log(item);
}

// Similar, but handles empty array gracefully
let queue2 = [];

do {
  let item = queue2.shift() ?? "empty";
  console.log(item);
} while (queue2.length);

Conclusion

JavaScript provides a rich set of loop mechanisms. Choosing the appropriate loop depends on the specific task, performance requirements, and coding style preferences. Understanding the nuances of each type empowers developers to write efficient and maintainable code.

The above is the detailed content of All About JavaScript Loops. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn