Looping Through Associative Arrays in Javascript

Jan 14, 2020 · 1 min. read

One way to iterate through an associative array is with "for in" loop:

For In Loop

let foodForLunch = {
  "fruit" : "apple",
  "vegetable" : "brocolli",
  "protein" : "steak",
  "starch" : "sweet potato"
};

for (let key in foodForLunch) {
  if (foodForLunch.hasOwnProperty(key)) {
    console.log(foodForLunch[key]); // prints apple broccoli...
  }
}

The function hasOwnProperty might strike you as odd. This checks to make sure that the property (key) being accessed is not inherited. For example, toString is a property of most objects, but probably not one you are trying to access in a loop.

You can also iterate through indexed arrays with this syntax:

let weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

for (let key in weekdays) {
  if (weekdays.hasOwnProperty(key)) {
    console.log(weekdays[key]); // prints Monday Tuesday...
  }
}

forEach Loop

A newer way to loop through arrays is with forEach:

Object.keys(foodForLunch).forEach(function(key, index) {
  console.log(this[key]); // prints apple broccoli...
}, foodForLunch);

Note that if you're interested in supporting IE11, you'll have to use a polyfill for forEach.

Which one to use?

I find the for in easier to understand. When performance is equal or similar, I always go with the code which is easier to understand, to save myself and others time and mental energy in the future.

If you use VS Code you can save yourself some typing with this snippet:

"for in loop": {
  "prefix": "/forin",
  "body": [
    "for (let ${1:key} in ${2}) {",
    "  if (array.hasOwnProperty($1)) {",
    "    $3",
    "  }",
    "}",
  ]