Tuhin Paul
Discuss the differences between for...of and for...in when iterating over objects.

Discuss the differences between for…of and for…in when iterating over objects.

By Tuhin Paul in JavaScript on Nov 11 2023
  • Jayraj Chhaya
    Nov, 2023 27

    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:

    1. const arr = [1, 2, 3];
    2. for (const element of arr) {
    3. console.log(element);
    4. }

    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:

    1. const obj = { a: 1, b: 2, c: 3 };
    2. for (const key in obj) {
    3. console.log(key, obj[key]);
    4. }

    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.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS