Looping Through JavaScript Objects

Intro picture

Before understanding how looping works, let us talk about JavaScript Objects. Remember, when we declare a variable using let, const, or var keywords? We set the identifier or variable name equals to a value. JavaScript variable can contain only one value, for example:

Where the fruit is the identifier or name of the variable and apple is the value. Let’s say, we bought some fresh fruits from the farmer’s market. How can we save all the fruits and fruit count into one variable? Yes, you guessed it right! We can use objects because they can contain many values. Specifically, key-value pairs contained inside curly braces. Key being the property and value is whatever we set it equals to. It could be a string, number, array, object or function definition. Before we begin looping, let refresh our memory on how to gain access to the key-value pairs of an object.

Accessing an object’s key-value pairs

Here, we are using bracket notation, (.) dot notation and Object.values method (object) for accessing the object’s value.

for…in loop

In the above example, we have names of the fruits as our key and count of each fruit as the value. So what if we want to count the total number of fruits?

Here we are iterating through each object property using a for..in loop. By using this method, we have now access to the values using the bracket notation on the object itself.

We usually use for..in loop to iterate over the properties of an object. Check if a value exists for a key, display the key-value pairs using console.log. This is actually a great debugging tool. A key thing to remember is, for..in is not recommended to use with arrays because the index order is important.

for…loop

There is another way of doing this, using Object.keys method that takes in an object as an argument and returns an array of keys.

In this example, we are getting back an array of keys, which we have saved it to a variable named fruitArray. Using a for…loop, we iterate through each fruitName (keys) in the array. Since we know that we can key into an object to get the value using bracket notation, we use this trick to get the fruit count and add it to the total count.

Happy Coding!

Loop Meme
Loop Meme

Coach @FlatironSchool

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store