How to Use for in Loop in JavaScript: Syntax and Examples
Use the
for in loop in JavaScript to iterate over all enumerable properties of an object. The syntax is for (key in object) { /* code */ }, where key is each property name. This loop is useful to access keys in objects but not recommended for arrays.Syntax
The for in loop syntax is:
key: a variable that holds the current property name (key) during each loop cycle.object: the object whose properties you want to loop through.- The loop runs once for each enumerable property in the object.
javascript
for (const key in object) { // code to run for each key }
Example
This example shows how to use for in to print all keys and values of an object.
javascript
const person = { name: 'Alice', age: 30, city: 'New York' }; for (const key in person) { console.log(key + ': ' + person[key]); }
Output
name: Alice
age: 30
city: New York
Common Pitfalls
Common mistakes when using for in include:
- Using it to loop over arrays, which can lead to unexpected order and inherited properties.
- Not checking if the property belongs directly to the object (not inherited) using
hasOwnProperty.
Here is a wrong and right way example:
javascript
// Wrong: looping over array with for in const arr = ['a', 'b', 'c']; for (const index in arr) { console.log(arr[index]); // works but order and extra properties may cause issues } // Right: use for of for arrays for (const value of arr) { console.log(value); } // Checking own properties const obj = Object.create({ inherited: 'no' }); obj.own = 'yes'; for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { console.log(key + ': ' + obj[key]); } }
Output
a
b
c
own: yes
Quick Reference
- Use for in to loop over object keys.
- Use hasOwnProperty to avoid inherited keys.
- Do not use for in for arrays; use
for ofinstead.
Key Takeaways
Use for in to loop over all enumerable keys of an object.
Always check hasOwnProperty to avoid inherited properties.
Avoid using for in to loop over arrays; use for of instead.
The loop variable holds the property name as a string.
for in loops over keys, not values directly.