Skip to content

Instantly share code, notes, and snippets.

@itsmacr8
Last active February 2, 2024 16:10
Show Gist options
  • Save itsmacr8/18e8b87b47ccaf14d528a6071a06a53b to your computer and use it in GitHub Desktop.
Save itsmacr8/18e8b87b47ccaf14d528a6071a06a53b to your computer and use it in GitHub Desktop.
This is a demonstration of how to use the for...in and for...of loops in JavaScript to iterate over an object. It shows the difference between the two loops, and explains why for...of is the best way to loop over an object.
const car = {engine: true};
const sportsCar = Object.create(car);
sportsCar.speed = 'fast';
console.log('The sportsCar object: ', sportsCar);
// Output: The sportsCar object: { speed: 'fast' }
// It loops over all the enumerable properties of the object,
// including those from its prototype chain.
for (const prop in sportsCar) {
console.log(`This is for in loop ${prop}, ${sportsCar[prop]}`);
}
// Output:
// This is for in loop speed, fast
// This is for in loop engine, true
// It only iterates over the object’s own properties, not the inherited ones.
for (const prop of Object.keys(sportsCar)) {
console.log(`This is for of loop ${prop}, ${sportsCar[prop]}`);
}
// Output:
// This is for of loop speed, fast
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment