For In Loop


The JavaScript for...in loop is a powerful iteration statement used to loop over the enumerable properties of an object. This loop is particularly useful for inspecting the properties of an object, but care should be taken when using it with arrays, as it can iterate over inherited properties and may not preserve the original order of elements.


Example 1: Basic Object Iteration

// a simple object representing a car
const car = {
  make: 'Honda',
  model: 'Civic',
  year: 2023
};

// using for...in to loop through car properties
for (const key in car) {
  console.log(`${key}: ${car[key]}`);
}

Explanation

This code defines an object car. The for...in loop iterates through each property of the car object. In each iteration, the key variable holds the property name (e.g., 'make'), and car[key] accesses the corresponding value.


Example 2: Ignoring Inherited Properties

// an object representing a user
const user = {
  name: 'Jane Doe',
  email: 'jane.doe@example.com'
};

// using hasOwnProperty to filter properties
for (const prop in user) {
  if (Object.prototype.hasOwnProperty.call(user, prop)) {
    console.log(`${prop}: ${user[prop]}`);
  }
}

Explanation

To avoid iterating over inherited properties from the object's prototype chain, it is best practice to use the hasOwnProperty() method. This ensures that only the object's own properties are processed in the loop.


Example 3: for...in with Arrays (Caution Advised)

// an array of colors
const colors = ['Red', 'Green', 'Blue'];

// iterating over an array with for...in
for (const index in colors) {
  console.log(`Index ${index}: ${colors[index]}`);
}

Explanation

While the for...in loop can iterate over array indices, it is generally not recommended for arrays. The loop may not visit elements in the correct order and can also iterate over non-numeric properties if any are added to the array.


Example 4: Modifying Object Properties

// an object with numerical values
const prices = {
  apple: 1.50,
  banana: 0.75,
  orange: 1.25
};

// doubling the price of each item
for (const item in prices) {
  prices[item] *= 2;
  console.log(`New price of ${item}: $${prices[item].toFixed(2)}`);
}

Explanation

The for...in loop allows you to directly access and modify the values of an object's properties. In this example, we iterate through the prices object and double the value of each fruit's price.


Example 5: Looping Through an Object with Mixed Data Types

// an object with various data types
const movie = {
  title: 'Inception',
  duration: 148,
  isReleased: true,
  director: { name: 'Christopher Nolan' }
};

// displaying property and its type
for (const key in movie) {
  console.log(`Property '${key}' has a type of '${typeof movie[key]}'`);
}

Explanation

This code demonstrates that a for...in loop can handle objects containing different data types, including strings, numbers, booleans, and even other objects. The typeof operator is used to show the data type of each property's value.


Example 6: Using for...in with null and undefined

// creating an object
const settings = {
  theme: 'dark',
  fontSize: 16,
  user: null
};

// the loop will not execute for a null or undefined object
for (const key in settings) {
  console.log(`${key}: ${settings[key]}`);
}

Explanation

The for...in loop gracefully handles properties with null values, iterating over them as it would with any other value. However, if the object itself is null or undefined, the loop will not execute and will not throw an error.


Example 7: Skipping Properties Based on a Condition

// an object representing a student's grades
const grades = {
  math: 95,
  science: 88,
  history: 75,
  art: 92
};

// only logging subjects with a grade above 90
for (const subject in grades) {
  if (grades[subject] > 90) {
    console.log(`${subject}: ${grades[subject]}`);
  }
}

Explanation

You can include conditional logic within a for...in loop to selectively process properties. This example iterates through the grades object but only prints the subjects where the grade is higher than 90.