Iterating (looping) through data collections is one of the most frequent tasks in frontend and backend engineering. Modern JavaScript provides specialized iteration constructs tailored specifically for arrays and objects.
for...of Loop (Recommended for Values)Iterates directly over the values of any iterable (Arrays, Strings, Sets):
.forEach() MethodFunctional iteration taking a callback:
Because objects are not directly iterable with for...of, modern JavaScript provides three static methods on Object:
Object.keys(): Looping through keysObject.values(): Looping through values directlyObject.entries() with Array Destructuring (Most Elegant!):for...in Loop (Object Keys & Caution)The for...in loop iterates over all enumerable property keys of an object:
for...in on Arrays!
for...in iterates over property names (as strings, like "0", "1"), does not guarantee numerical order, and can traverse prototype chain properties. For arrays, always use for...of or standard for loops!| Data Structure | Best Modern Choice | Alternative |
|---|---|---|
| Array | for...of or .forEach() | Standard for (let i = 0; ...) |
| Object | Object.entries() with for...of | Object.keys() or for...in |
| String | for...of | Standard for loop |
Object.entries(user) return?for...in to iterate through arrays?Object.keys({ a: 1, b: 2 }) return?array.forEach() loop using the break keyword?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Object Basics and Properties | Working with Date Object |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.