How to use For Of Loop In Javascript

In this approach, we create a function findPropertyValue() using a for-of loop to iterate through objects based on a specific object ID, searching for a property’s value accordingly. The matching object property value is returned as the output.

Example: The below code uses the JavaScript for-of loop to find property values in an array of objects.

Javascript




const objectsArray = [
    { id: 1, name: "w3wiki" },
    { id: 2, name: "Computer Science" },
    { id: 3, name: "Portal" },
    { id: 4, name: "For Geeks" },
    { id: 5, name: "GFG" },
]
 
function getPropertyValue(objectID) {
    for (const obj of objectsArray) {
        if (obj.id == objectID) {  //If-else condition
            return obj.name;
        } else {
            continue;
        }
    }
    return null;
}
 
//Prints "name" property value of object with "id" 3
console.log(getPropertyValue(3));


Output

Portal


How to Find Property Values in an Array of Object using if/else Condition in JavaScript ?

Finding property values in an array of objects using if/else condition is particularly useful when there is a collection of objects.

Table of Content

  • Using Array Find Method
  • Using Array Filter Method
  • Using For Of Loop

Similar Reads

Using Array Find Method

The array find method loop in JavaScript is used to retrieve the first element in an array that satisfies a given condition. In this approach, using the find() method, we create a function findPropertyValue() to filter objects in the ‘objectsArray’ array based on a specific object id, returning an object property value....

Using Array Filter Method

...

Using For Of Loop

In this approach, using the filter() method, we create a function findPropertyValue() to filter objects in the ‘objectsArray’ array based on a specific object id, returning an object property value in the form of a new array containing this particular object property that satisfies the specified condition....

Contact Us