Member-only story

Difference between for loop and foreach loop in JavaScript

Pravin M
2 min readFeb 15, 2024

--

Difference between for loop and foreach loop in JavaScript

Source:- Difference between for loop and foreach loop in JavaScript

For more questions and answers visit our website at Frontend Interview Questions

In JavaScript, both the for loop and the forEach loop are used for iterating over elements in an array or other iterable objects. However, they have distinct characteristics and use cases that set them apart.

`for` Loop:

The `for` loop is a traditional loop construct that provides more control over the iteration process. It consists of three parts: initialization, condition, and iteration expression.


for (initialization; condition; iteration) {
// Code to be executed in each iteration
}

Example:


const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}

`forEach` Loop:

The `forEach` loop is a higher-order function provided by arrays that simplifies the iteration process. It takes a callback function as its argument and applies that function to each element in the array.


array.forEach(callback(currentValue, index, array) {
// Code to be executed for each element
});

--

--

Pravin M
Pravin M

Written by Pravin M

I am a frontend developer with 10+ years of experience Blog :- https://www.frontendinterviewquestions.com

No responses yet