Introduction
In JavaScript, the for…in loop serves the purpose of traversing through the properties of an object. It exclusively iterates over the keys of objects where the enumerable property is designated as "true."
The for…in loop provides a mechanism to iterate over and retrieve each key or property name belonging to an object.
Syntax of JavaScript for…in Loop
The syntax of for…in loop is as follows:
for(key in object){
//code to execute
}
key: A variable utilized to retain an individual key associated with the object.
object: The object containing the keys that we wish to loop through.
How does JavaScript for…in Loop Work?
There are some key points to showcase the working of JavaScript for…in Loop:
- In the first iteration, the key variable is assigned the first key of the object. Then, the body of the loop is executed.
- In the second iteration, the key variable is assigned the next key of the object. Then, the body of the loop is executed again.
- This process continues until there are no more keys over which to iterate.
Example 1
const items = {Apple: 2, Banana: 12, Orange: 5};
for(const fruit in items){
console.log(items[fruit]);
}
Output:
2
12
5
Example 2
const salaries = {
Jhon: 24000,
Shaun: 34000,
Lea: 55000
};
// use for...in to loop through
// properties of salaries
for (let key in salaries) {
// access object key using [ ]
// add a $ symbol before the key
let salary = "$" + salaries[key];
// display the values
console.log(`${key}: ${salary}`);
};
Output:
Jhon: $14000
Shaun: $24000
Lea: $15000
Explanation
In this instance, we employed the for…in loop to traverse the properties of the salaries contained within the object. Subsequently, we appended the string $ to each value associated with the object.
For Loop within a For-in Loop
In this method, a for loop is embedded inside a for-in loop. The for-in loop in JavaScript allows iteration over the properties of an object, while the inner for loop can execute further iterations corresponding to each property.
Syntax
The structure of a for loop nested inside a for-in loop is outlined below:
for (let key in obj) {
for (let i = 0; i < limit; i++) {
// Code to execute
}
}
Example
This program demonstrates the concept of nested loops, where a traditional for loop is implemented inside a for-in loop using JavaScript.
// Example of nested loops in JavaScript
const fruits = { apple: 5, banana: 3, orange: 7 };
for (const key in fruits) {
console.log(`Fruit: ${key}`);
for (let i = 0; i < fruits[key]; i++) {
console.log(` - Count: ${i + 1}`);
}
}
Explanation:
- The code begins by defining an object named
fruits, which contains various types of fruits as keys along with their respective quantities as values. - The outer
for-inloop iterates over each key in thefruitsobject. In this instance, thekeyvariable will take on the valuesapple,banana, andorange. - Within the body of the
for-inloop, the current fruit's name is logged to the console. - Subsequently, a
forloop is employed, which runs from0up to the number of fruit quantities indicated byfruits[key]. - Within this inner loop, the current count of each fruit is displayed, incremented by one for better readability.
Output:
Running this code will produce the following output in the console:
Fruit: apple
- Count: 1
- Count: 2
- Count: 3
- Count: 4
- Count: 5
Fruit: banana
- Count: 1
- Count: 2
- Count: 3
Fruit: orange
- Count: 1
- Count: 2
- Count: 3
- Count: 4
- Count: 5
- Count: 6
- Count: 7
This program effectively illustrates how nested loops can be utilized to handle data structures, allowing developers to process multiple layers of information efficiently.
Example
const obj = { p: 5, q: 4, r: 3 };
for (let key in obj) {
console.log(`Key: ${key}`);
for (let i = 1; i <= 3; i++) {
console.log(` Value multiplied by ${i}: ${obj[key] * i}`);
}
}
Output:
Key: p
Value multiplied by 1: 5
Value multiplied by 2: 10
Value multiplied by 3: 15
Key: q
Value multiplied by 1: 4
Value multiplied by 2: 8
Value multiplied by 3: 12
Key: r
Value multiplied by 1: 3
Value multiplied by 2: 6
Value multiplied by 3: 9
Important Facts About JavaScript for…in Loop
The use of the for…in loop in JavaScript is discouraged when working with arrays, particularly when it is essential to preserve the indexing order.
In JavaScript, the sequence in which elements are iterated over using the for…in loop is dependent on the specific implementation. Consequently, this means that the array elements might not be accessed in the anticipated order.
At times, the sequence in which properties are traversed may not correspond to the order in which they were established within the object.
Key features of JavaScript for…in Loop
Designed for Objects
The JavaScript for…in loop is specifically designed to traverse the enumerable properties of objects. This includes not only the properties that belong directly to the object itself but also those that are inherited through the prototype chain.
Accessing Property keys
The syntax is straightforward for accessing each key within the object, enabling the developer to perform additional manipulation or retrieve properties of the object.
Enumeration Orders
The order of iteration for the JavaScript for…in loop is not assured to remain consistent across various JavaScript engines.
Versatility
The for…in loop is capable of iterating through the properties of both user-defined custom objects and various built-in object types, including objects, arrays, strings, and more.
Conclusion
The for…in loop in JavaScript serves as a crucial tool for traversing the keys of an object, allowing programmers to run code for every enumerable property present.
JavaScript for…in Loop- FAQs
What is a for-in loop in JavaScript?
In JavaScript, the for…in loop serves as a control mechanism designed to traverse the enumerable properties of an object. By utilizing this loop, you are able to retrieve the keys of an object sequentially, one at a time.
How does the for-in loop work?
In JavaScript, the for…in loop serves the purpose of traversing the properties of an object. During each iteration, the key variable is assigned the current property name, and the associated code block is executed.
What distinguishes for…in loops from for…of loops?
Both for…in and for…of loops are utilized in JavaScript for iterating over collections, but they serve different purposes and operate on different types of data structures.
- for…in Loop:
- The for…in loop is primarily designed to iterate over the enumerable properties of an object.
- It is important to note that this loop traverses keys (property names) rather than the values themselves.
- Example:
- for…of Loop:
- In contrast, the for…of loop is intended for iterating over iterable objects, such as arrays, strings, and other collections that follow the iterable protocol.
- This loop retrieves the values directly, rather than the keys.
- Example:
const person = { name: 'Alice', age: 25, city: 'New York' };
for (const key in person) {
console.log(key); // Outputs: name, age, city
}
const numbers = [1, 2, 3, 4, 5];
for (const number of numbers) {
console.log(number); // Outputs: 1, 2, 3, 4, 5
}
In summary, utilize the for…in loop when you need to access the keys of an object, while the for…of loop should be your choice when you want to work directly with the values of iterable entities.
The key distinction between for…in and for…of loops in JavaScript lies in their iteration methods: the for…in loop traverses the enumerable string properties of an object, whereas the for…of loop goes through the values of iterable objects such as arrays, strings, and more.