JavaScript For In Loop
The JavaScript for…in loop iterates over the properties of an object. It allows you to access each key or property name of an object.
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
// 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]);
}
Output
1 2 3 4 5
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.
JavaScript for-in Loop – FAQs
What is a for-in loop in JavaScript?
A for-in loop is a control structure that allows you to iterate over the enumerable properties of an object. This loop is used to access the keys of an object one by one.
What is the basic syntax of a for-in loop?
The basic syntax of a for-in loop includes the for keyword, followed by a variable to hold each key, the in keyword, and the object to iterate over. The code block to be executed for each key is placed inside curly braces.
How does the for-in loop work?
The for-in loop iterates over the enumerable properties of an object. For each property, the loop assigns the property key to the specified variable and executes the code block.
What is the difference between for-in and for-of loops?
- for-in loop: Iterates over the enumerable properties (keys) of an object.
- for-of loop: Iterates over the values of an iterable object (such as arrays, strings, maps, etc.).
Can a for-in loop be used with arrays?
Yes, a for-in loop can be used with arrays, but it is not recommended because it iterates over all enumerable properties, including inherited properties. It is better to use a for-of loop or a traditional for loop for arrays.