Use For-In Loop to Iterate Through Array Elements
In this step, you'll learn about the for-in loop in JavaScript, which provides an easy way to iterate through the properties of an object or elements of an array.
Create a new file named forInLoop.js
in the ~/project
directory using the WebIDE:
// Iterating through an array using for-in loop
let fruits = ["apple", "banana", "cherry", "date"];
console.log("Iterating through Array Indices:");
for (let index in fruits) {
console.log(`Index: ${index}, Fruit: ${fruits[index]}`);
}
// Iterating through an object using for-in loop
let student = {
name: "John Doe",
age: 22,
major: "Computer Science",
gpa: 3.8
};
console.log("\nIterating through Object Properties:");
for (let property in student) {
console.log(`${property}: ${student[property]}`);
}
// Practical example: Calculating total price of items
let shoppingCart = [
{ name: "Laptop", price: 1000 },
{ name: "Headphones", price: 100 },
{ name: "Mouse", price: 50 }
];
console.log("\nCalculating Total Price:");
let totalPrice = 0;
for (let index in shoppingCart) {
totalPrice += shoppingCart[index].price;
}
console.log(`Total Price: $${totalPrice}`);
Run the JavaScript file to see the for-in loop in action:
node ~/project/forInLoop.js
Example output:
Iterating through Array Indices:
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry
Index: 3, Fruit: date
Iterating through Object Properties:
name: John Doe
age: 22
major: Computer Science
gpa: 3.8
Calculating Total Price:
Total Price: $1150
Key points about for-in loops:
- Works with both arrays and objects
- Iterates through indices (for arrays) or properties (for objects)
- Provides a simple way to access elements without using traditional index-based loops
- Be cautious when using with arrays, as it iterates through all enumerable properties
Let's explore another example to demonstrate its flexibility:
// Using for-in loop to filter and transform data
let grades = {
math: 85,
science: 92,
english: 78,
history: 88
};
console.log("Filtering Grades Above 80:");
for (let subject in grades) {
if (grades[subject] > 80) {
console.log(`${subject}: ${grades[subject]}`);
}
}
Run the file again:
node ~/project/forInLoop.js
Example output:
Filtering Grades Above 80:
math: 85
science: 92
history: 88