How do you iterate over object properties?
JavaScriptThe short answer
The main ways are Object.keys() (get keys), Object.values() (get values), Object.entries() (get key-value pairs), and for...in (loop over all enumerable properties including inherited ones). Object.keys/values/entries are preferred because they only return the object's own properties.
Object.keys
Returns an array of the object's own property names:
const user = { name: 'John', age: 30, city: 'NYC' };Object.keys(user); // ["name", "age", "city"]Object.keys(user).forEach((key) => { console.log(`${key}: ${user[key]}`);});Object.values
Returns an array of the values:
Object.values(user); // ["John", 30, "NYC"]Object.entries
Returns an array of [key, value] pairs — the most useful for iteration:
Object.entries(user); // [["name", "John"], ["age", 30], ["city", "NYC"]]for (const [key, value] of Object.entries(user)) { console.log(`${key}: ${value}`);}for...in
Loops over all enumerable properties, including inherited ones:
for (const key in user) { console.log(`${key}: ${user[key]}`);}If you use for...in, always check hasOwnProperty to skip inherited properties:
for (const key in user) { if (user.hasOwnProperty(key)) { console.log(`${key}: ${user[key]}`); }}Or just use Object.keys() / Object.entries() which do not include inherited properties.
Interview Tip
Show Object.entries() with destructuring as the cleanest approach. Mention that for...in includes inherited properties (which is why Object.keys is preferred). This is a quick question — keep examples short.
Why interviewers ask this
This tests basic JavaScript knowledge. Interviewers want to see if you know the different methods and which ones include inherited properties.