JavaScript For In Loop (original) (raw)
Last Updated : 20 Nov, 2024
TheJavaScript for…in loop iterates over the properties of an object. It allows you to access each key or property name of an object.
JavaScript ``
const car = { make: "Toyota", model: "Corolla", year: 2020 };
for (let key in car) {
console.log(${key}: ${car[key]}
);
}
``
Output
make: Toyota model: Corolla year: 2020
**Syntax
for (key in object) { // Code}
The **for…in loop can also works to iterate over the properties of an array, but it is not recommended. for..in is mainly suitable for objects.
For arrays, we should use below loops.
- For of Loop if we need to put continue or break in the loop
- forEach() if we need execute something for all elements without any condition JavaScript `
// Example of for in for arrays // Not a recommended way to traverse // an array const a = [1, 2, 3, 4, 5];
for (const i in a) { console.log(a[i]); }
`
**Important Facts About for in Loop
- The **for…in loop is not recommended for use with arrays if maintaining index order is important.
- The order of iteration in **for…in loop is implementation-dependent, means the array elements may not be accessed in the expected sequence.
- The order in which properties are iterated may not match the properties that are defined in the object.