Comparison of for, forEach, and map in JavaScript


1. for Loop

• Description: A general-purpose loop that can be used to iterate over anything, not just arrays. It gives you complete control over the iteration process.

• Syntax:

for (let i = 0; i < array.length; i++) {

    // Do something with array[i]

}

• Key Points:

○ Manual control over iteration (e.g., starting point, ending condition, step size).

○ Can be used to break out of the loop early using break or skip iterations using continue.

○ Not limited to arrays (can be used for iterating over strings, objects, or ranges).

• Use Case: When you need fine-grained control over iteration or performance-critical tasks.


2. forEach

• Description: An array method that executes a provided function once for each array element. It is a simpler and cleaner way to iterate through arrays.

• Syntax:

array.forEach((element, index) => {

    // Do something with element

});

• Key Points:

○ Cannot break or skip iterations (break and continue don't work).

○ Executes the callback function for each array element.

○ Automatically handles the iteration, making it more concise than for.

○ Does not return anything (undefined).

• Use Case: When you want to iterate through an array and perform an operation on each element, without modifying the array or creating a new one.


3. map

• Description: An array method that creates a new array by applying a provided function to each element of the original array.

• Syntax:

const newArray = array.map((element, index) => {

    return element * 2; // Example operation

});

• Key Points:

○ Returns a new array with the transformed elements.

○ Does not modify the original array.

○ Commonly used for data transformation tasks.

• Use Case: When you want to transform each element of an array and store the results in a new array.










Comments