Loop through an array in JavaScript
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In JavaScript, there are several ways to loop through an array. Here are some of the most common methods:
1. for Loop
The classic for loop gives you control over the index and is suitable when you need to access both the index and value.
2. for...of Loop (ES6)
The for...of loop iterates directly over the values in the array, making it concise and easy to use.
3. forEach() Method
The forEach() method executes a function for each element in the array. It’s concise and functional, often preferred for simple iteration.
4. map() Method
The map() method creates a new array by applying a function to each element. It’s useful when you want to transform each element in the array.
5. for...in Loop (Not Recommended for Arrays)
The for...in loop iterates over enumerable properties, including array indices. However, it's generally used for objects, as it may include inherited properties and isn’t ideal for array iteration.
Summary
- Use
fororfor...offor general iteration. - Use
forEach()for concise, functional iteration. - Use
map()when you need to transform elements and return a new array. - Avoid
for...infor arrays, as it’s primarily intended for objects.
Related reading
- Set cellpadding and cellspacing in CSS?
- What does the !! operator do in JavaScript?
- What is the --save option for npm install?
- What is the difference between call and apply?
- What is the difference between "let" and "var"?
- What is the most efficient way to deep clone an object in JavaScript?
- Which equals operator (== vs ===) should be used in JavaScript comparisons?
- Why does my JavaScript code receive a "No ''Access-Control-Allow-Origin'' header is present on the requested resource" error, while Postman does not?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.