Explain Codes LogoExplain Codes Logo

For..in loops in JavaScript - key value pairs

javascript
for-in-loops
javascript-iteration
object-entries
Anton ShumikhinbyAnton Shumikhin·Nov 23, 2024
TLDR

For those of you in a hurry, here's a quick snippet that shows you how to access key-value pairs in JavaScript objects, using a **for...in** loop and a **hasOwnProperty** check 101:

const obj = { a: 1, b: 2, c: 3 }; // Loop over each property in object for (const key in obj) { // "Is this my property or did I inherit it?" - JavaScript object, probably if (obj.hasOwnProperty(key)) { console.log(`Key: ${key}, Value: ${obj[key]}`); } }

This way you're owning it, iterating only over the object's specific properties, not the ones it borrowed from its well-meaning prototype.

The many faces of iteration, and when to use them

Different tasks, different environments, but same need for iteration. Here are few ways to meet that need with style:

ES6: for..of with Object.entries

for..of with Object.entries is like the hot new couple on the JavaScript block (hey, it's ES6 town here!). Let's introduce them to our object:

const obj = { a: 1, b: 2, c: 3 }; // Object.entries + for..of = Dream team for (const [key, value] of Object.entries(obj)) { console.log(`Key: ${key}, Value: ${value}`); }

Your gateway to array methods: Object.keys

Want to use your favourite array methods, but stuck with an object? Object.keys is your ticket to a functional programming party:

// invited: Just the keys, no plus ones Object.keys(obj).forEach(key => { console.log(`Key: ${key}, Value: ${obj[key]}`); });

The Unlockers: Object.values and Object.entries

Unleash the power of arrays on your object with Object.values and Object.entries.

const values = Object.values(obj); // "Just the values, ma'am" const entries = Object.entries(obj); // Who doesn't love a good entry?

Beware the quirks: best practices and common pitfalls

Every JavaScript veteran knows that for...in demands respect. It has rules, and expectations, sometimes bordering on quirks. But hey, don't we all?

HasOwnProperty: check your lineage

While iterating with for..in, you don't want to accidentally take some prototypes properties. So ask every property: "do you really belong here?"

for (const key in obj) { // No infiltrators, please. if (typeof obj[key] !== 'function' && obj.hasOwnProperty(key)) { console.log(`Key: ${key}, Value: ${obj[key]}`); } }

ES6's got you covered

Ever since Object.entries swiped right on JavaScript, it has been the preferred choice over for...in, notably for avoiding prototype chain issues.