Discuss the differences between for…of and for…in when iterating over objects.
When it comes to iterating over objects in JavaScript, the for…of and for…in loops serve different purposes and have distinct behaviors.
The for…of loop is used to iterate over iterable objects such as arrays, strings, and collections. It allows you to access the values of the elements directly without worrying about the underlying structure of the object. Here’s an example:
const arr = [1, 2, 3];for (const element of arr) { console.log(element);}
const arr = [1, 2, 3];
for (const element of arr) {
console.log(element);
}
On the other hand, the for…in loop is used to iterate over the enumerable properties of an object. It traverses through the keys of the object, allowing you to access both the keys and their corresponding values. Here’s an example:
const obj = { a: 1, b: 2, c: 3 };for (const key in obj) { console.log(key, obj[key]);}
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(key, obj[key]);
It’s important to note that the for…in loop also iterates over the inherited properties of an object, including properties from the prototype chain. To avoid this, you can use the hasOwnProperty method to check if the property belongs to the object itself.