Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax of the 'for-in' Loop
3.
Important Points about the 'for-in' Loop
3.1.
Enumerating over properties
3.2.
Order of iteration
3.3.
Filtering properties
4.
Examples of Using the 'for-in' Loop
4.1.
Example 1: Displaying Object Properties
4.2.
Example 2: Calculating the Average Score
4.3.
Example 3: Filtering Specific Properties
5.
Supported Browsers for the 'for-in' Loop
6.
Frequently Asked Questions
6.1.
Can the 'for-in' loop be used for arrays?
6.2.
Does the 'for-in' loop iterate over all properties?
6.3.
How can I stop the iteration in a 'for-in' loop?
7.
Conclusion
Last Updated: Jun 1, 2024
Easy

For in Loop in Javascript

Author Ravi Khorwal
0 upvote

Introduction

JavaScript is a crucial tool in the world of web development, allowing us to create interactive and dynamic web pages. Among its many features, the 'for-in' loop stands out for its ability to iterate over the properties of an object. This loop is especially useful when you need to handle objects where the number of properties is not fixed or directly known. 

For in Loop in Javascript

In this article, we'll understand how the 'for-in' loop works, its syntax with examples to show its practical use. 

Syntax of the 'for-in' Loop

The 'for-in' loop in JavaScript provides a straightforward way to loop through properties of an object. This loop is designed to iterate over the enumerable properties of an object, which includes properties that are not symbols and are directly upon the object. The syntax for using the 'for-in' loop is simple and can be quickly grasped even by those new to programming in JavaScript.

Here's how it looks:

for (var key in object) {
    // code to execute for each property
}


In this structure:

  • key represents the variable that we use to store the property name during each iteration.
     
  • object is the object whose properties the loop will iterate over.
     
  • The code inside the braces { } is executed for each property.

For example, if we have an object that stores the details of a book, like so:

var book = {
    title: "JavaScript Basics",
    author: "Raman Seth",
    year: 2021
};


We can use the 'for-in' loop to print all the properties of the book object:

for (var key in book) {
    console.log(key + " : " + book[key]);
}


This loop will output:

title : JavaScript Basics
author : Raman Seth
year : 2021


Each property name and its value are accessed and printed, making the 'for-in' loop a useful tool for handling objects.

Important Points about the 'for-in' Loop

When using the 'for-in' loop, it's important to understand a few key aspects to avoid common mistakes and to use this loop effectively in your JavaScript code.

Enumerating over properties

The 'for-in' loop goes through all enumerable properties of an object. This includes both the object's own properties and those it inherits from its prototype chain. Sometimes, you might not want to include inherited properties. To ensure you're only accessing the object's own properties, you can use the hasOwnProperty() method:

for (var key in book) {
    if (book.hasOwnProperty(key)) {
        console.log(key + " : " + book[key]);
    }
}


This modification to the loop will check if the property belongs directly to the book object, and not inherited from its prototype.

Order of iteration

The order in which the 'for-in' loop iterates over the properties is not guaranteed. For many types of programming tasks, the order of processing these properties may be important. If you need to process properties or elements in a specific order, consider using an array or another method that guarantees order, like the Object.keys() method combined with forEach:

Object.keys(book).forEach(function(key) {
    console.log(key + " : " + book[key]);
});

Filtering properties

Besides checking for own properties, sometimes you may need to filter out properties based on some criteria. For example, you might only want to work with properties that have numeric values or those that meet a certain condition. Adding a conditional statement inside the loop can help achieve this:

for (var key in book) {
    if (typeof book[key] === 'number') {
        console.log(key + " : " + book[key]);
    }
}

Examples of Using the 'for-in' Loop

Now, let’s look at a few practical examples. These examples will show how the loop can be adapted for different scenarios, making it a versatile tool for developers.

Example 1: Displaying Object Properties

Suppose we have an object that represents a student's report card with grades in different subjects:

var reportCard = {
    math: 95,
    science: 88,
    history: 74
};


Using the 'for-in' loop, we can easily display each subject and the corresponding grade:

for (var subject in reportCard) {
    console.log(subject + " grade: " + reportCard[subject]);
}


This code will output:

math grade: 95
science grade: 88
history grade: 74

Example 2: Calculating the Average Score

Let’s extend the first example by calculating the average score from the report card:

var totalScore = 0;
var subjectCount = 0;
for (var subject in reportCard) {
    totalScore += reportCard[subject];
    subjectCount++;
}
var averageScore = totalScore / subjectCount;
console.log("Average Score: " + averageScore);


This loop goes through each grade, adds it to totalScore, and counts the subjects using subjectCount. It then calculates the average score and prints it out. This demonstrates the loop’s ability to handle numerical data and perform calculations across an object's properties.

Example 3: Filtering Specific Properties

Imagine we only want to print the grades that are above 85:

for (var subject in reportCard) {
    if (reportCard[subject] > 85) {
        console.log(subject + " grade: " + reportCard[subject]);
    }
}


This code checks each grade, and if it’s above 85, it prints the subject and grade. This example showcases how the 'for-in' loop can be used to filter data based on specific conditions.

Supported Browsers for the 'for-in' Loop

The 'for-in' loop is widely supported across all major web browsers, making it a reliable tool for web developers. This universal support is crucial because it ensures that web applications using the 'for-in' loop will work consistently, regardless of the user's browser choice.

Compatibility Details:

  • Google Chrome: Full support
     
  • Mozilla Firefox: Full support
     
  • Safari: Full support
     
  • Opera: Full support
     
  • Microsoft Edge: Full support
     
  • Internet Explorer: Full support
     

This broad compatibility means that when you use the 'for-in' loop in your JavaScript code, you don't have to worry about it not working in some browsers. Whether your website visitors are using the latest version of Chrome, older versions of Internet Explorer, or anything in between, the 'for-in' loop will function correctly.

Frequently Asked Questions

Can the 'for-in' loop be used for arrays?

Yes, but it's not recommended. While the 'for-in' loop can iterate over array indices, it doesn't guarantee the order of iteration and may include inherited properties. For arrays, methods like forEach(), for, or for-of loops are more suitable because they provide better control and reliability for array operations.

Does the 'for-in' loop iterate over all properties?

The 'for-in' loop iterates over all enumerable properties, including those inherited from an object’s prototype chain. To iterate only over the object’s own properties, use the hasOwnProperty() method within the loop to filter out inherited properties.

How can I stop the iteration in a 'for-in' loop?

To break out of a 'for-in' loop, you can use the break statement. If you need to skip to the next iteration without completing the current one, use the continue statement. Both are useful for controlling the flow based on specific conditions during the loop.

Conclusion

In this article, we have learned the fundamentals of the 'for-in' loop in JavaScript, covering its syntax, key considerations, practical examples, and browser support. Understanding how to effectively use the 'for-in' loop enhances your ability to manage and manipulate object properties in your coding projects. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass