ES6 - Loops
ES6+ - Modern Looping Constructs
Section titled “ES6+ - Modern Looping Constructs”Loops are fundamental control flow structures that allow you to execute a block of code repeatedly. Each execution of the loop body is called an iteration. JavaScript offers several types of loops for different scenarios.
Classification of Loops:
- Definite Loops: Execute a known number of times. The primary example is the
forloop, and its modern variantfor...offor iterables. - Indefinite Loops: Execute as long as a certain condition remains true. Examples include
whileanddo...whileloops.
Definite Loops
Section titled “Definite Loops”These loops are used when the number of iterations is determined before the loop starts.
1. The for loop (Traditional)
Section titled “1. The for loop (Traditional)”The traditional for loop consists of three optional expressions, followed by a statement or block of statements executed in the loop.
for (initialization; condition; final-expression) { // statements to execute}Example:
for (let i = 0; i < 5; i++) { console.log(`Iteration ${i}`);}// Output: Iteration 0, Iteration 1, ..., Iteration 42. The for...in loop
Section titled “2. The for...in loop”The for...in loop iterates over all enumerable string properties of an object (ignoring Symbols), including inherited enumerable properties. It is generally not recommended for iterating over arrays because the order of iteration is not guaranteed, and it may iterate over non-element properties.
for (const key in object) { if (Object.hasOwnProperty.call(object, key)) { // statements using object[key] }}Example:
const person = { name: 'Alice', age: 30, city: 'New York' };for (const property in person) { console.log(`${property}: ${person[property]}`);}// Output: name: Alice, age: 30, city: New York (order may vary)Always use Object.hasOwnProperty.call(object, key) or object.hasOwnProperty(key) to ensure you are processing only the object’s own properties.
3. The for...of loop (ES6+ Recommended for Iterables)
Section titled “3. The for...of loop (ES6+ Recommended for Iterables)”The for...of loop, introduced in ES6, creates a loop iterating over iterable objects (including Array, Map, Set, String, TypedArray, arguments object, and user-defined iterables). It iterates over the values of the iterable, not the keys/indices.
for (const value of iterable) { // statements using value}Example with Array:
const colors = ['red', 'green', 'blue'];for (const color of colors) { console.log(color);}// Output: red, green, blueExample with String:
const message = 'Hello';for (const char of message) { console.log(char);}// Output: H, e, l, l, oThis is the preferred way to iterate over the values of arrays and other iterable collections.
Indefinite Loops
Section titled “Indefinite Loops”These loops are used when the number of iterations is not known beforehand and depends on a condition.
1. The while loop
Section titled “1. The while loop”The while loop executes its statements as long as a specified condition evaluates to true. The condition is checked before each iteration.
while (condition) { // statements}Example:
let count = 0;while (count < 3) { console.log(`Count is ${count}`); count++;}// Output: Count is 0, Count is 1, Count is 22. The do...while loop
Section titled “2. The do...while loop”The do...while loop is similar to while, but the condition is checked after executing the statements. This ensures the loop body executes at least once.
do { // statements} while (condition);Example:
let num = 5;do { console.log(`Number is ${num}`); num++; // This will not run in this specific example as condition is immediately false} while (num < 5); // Condition is false after first iteration// Output: Number is 5
let k = 0;do { console.log(`k is ${k}`); k++;} while (k < 3);// Output: k is 0, k is 1, k is 2Loop Control Statements
Section titled “Loop Control Statements”| Statement | Description |
|---|---|
break | Terminates the current loop (or switch or labeled statement) and transfers program control to the statement following the terminated statement. |
continue | Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration. |
Example with break and continue:
Section titled “Example with break and continue:”for (let i = 0; i < 10; i++) { if (i === 3) { continue; // Skip iteration when i is 3 } if (i === 7) { break; // Exit loop when i is 7 } console.log(i);}// Output: 0, 1, 2, 4, 5, 6Using Labels to Control Flow
Section titled “Using Labels to Control Flow”A label is an identifier followed by a colon (:) that can be applied to a loop or a block of code. break and continue can use these labels to specify which loop or block to target, which is particularly useful in nested loops. However, overuse of labels can make code harder to read and understand, so they should be used sparingly.
Example with labeled break:
Section titled “Example with labeled break:”outerLoop: // Label for the outer loopfor (let i = 0; i < 3; i++) { console.log(`Outer: ${i}`); innerLoop: // Label for the inner loop for (let j = 0; j < 3; j++) { if (i === 1 && j === 1) { break outerLoop; // Breaks out of both loops } console.log(` Inner: ${j}`); }}// Output:// Outer: 0// Inner: 0// Inner: 1// Inner: 2// Outer: 1// Inner: 0Line breaks are not allowed between the continue or break statement and its label name. Also, there should not be any other statement in between a label name and its associated loop.