jsRant asked this 7 years ago

Javascript: What is the correct way to loop over array of objects for, for..of?

I have

var arr = [
    {
        name: 'a',
        value: 1
    },
    {
        name: 'b',
        value: 2
    },
    {
        name: 'c',
        value: 3
    }
];

What is the best way to iterate the array and print all properties of each object?

I am doing

for(var i=0;i<arr.length;i++)
            console.log(arr[i].name);

I have heard i shouldn't use for...in because for...in works best for iterating on properties of objects (key-value pairs) and shouldn't be used on arrays directly.

What about for...of?


Best Answer by Guest 6 years ago

For..of loop can be written as follows

var arr = [
    {
        name: 'a',
        value: 1
    },
    {
        name: 'b',
        value: 2
    },
    {
        name: 'c',
        value: 3
    }
];

for (let val of arr) {
    console.log(val);
}