Choosing Between for..in Loops and Object.values() in JavaScript

To determine whether to use a for…in loop or Object.values, consider a scenario with two objects


const Product = {
    name:"product1",
    price:100,
}

const ProductInvoice = {
    invoiceno : "invoice1",
    customer : "customer1", 
}


These objects are linked to each other in the prototype chain.


Object.setPrototypeOf(ProductInvoice, Product);

Now, you iterate and list the values with for..in loop,


for (const key in ProductInvoice) {
    console.log(ProductInvoice[key]);
}


The expected output will be as demonstrated below:

The output above is obtained because the for…in loop iterates over all enumerable properties of an object, including those inherited from its prototype chain.

However, if you want to iterate over and list only the enumerable properties of an object, excluding those inherited from the prototype chain, you should use Object.values().


let p1 = Object.values(ProductInvoice);
console.log(p1);


The expected output will be as demonstrated below:

Further, you can use for..of the loop to print these values individually.


for (const v of Object.values(ProductInvoice)) {
    console.log(v);
}

The expected output will be as demonstrated below:

So, to summarize:

  1. The for…in loop iterates through all enumerable properties of an object, including inherited ones.
  2. The Object.values() method returns an array with the values of all enumerable properties of an object, excluding values from its prototype chain.

Let me know what you will use more often in your project.


Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading