The Wayback Machine - https://web.archive.org/web/20240806150711/https://www.geeksforgeeks.org/for-in-loop-in-javascript/
Open In App

JavaScript for-in Loop

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

The for-in loop in JavaScript iterates over the enumerable properties of an object, executing a specified block of code for each property. It’s commonly used for iterating through object properties or elements in an array.

Syntax:

for (let i in obj1) {
// Prints all the keys in
// obj1 on the console
console.log(i);
}

for in Loop Important Points

  • Use the for-in loop to iterate over non-array objects. Even though we can use a for-in loop for an array, it is generally not recommended. Instead, use a for-of loop for looping over an array.
  • The properties iterated with the for-in loop also include the properties of the objects higher in the Prototype chain.
  • The order in which properties are iterated may not match the properties that are defined in the object.

for-in Loop Examples

Example: A simple example to illustrate the for-in loop over an array.

JavaScript
const array = [1, 2, 3, 4, 5];

// Using for-of loop for array
for (const value in array) {
  console.log(array[value]);
}

Output
1
2
3
4
5

Example 2: For-in loop iterates over the properties of an object and its prototype chain’s properties. If we want to display both properties of the “student1” object which belongs to that object only and the prototype chain, then we can perform it by for in loop.

javascript
const courses = {

    // Declaring a courses object
    firstCourse: "C++ STL",
    secondCourse: "DSA Self Paced",
    thirdCourse: "CS Core Subjects"
};

// Creating a new empty object with
// prototype set to courses object
const student1 = Object.create(courses);

// Defining student1 properties and methods
student1.id = 123;
student1.firstName = "Prakhar";
student1.showEnrolledCourses = function () {
    console.log(courses);
}

// Iterating over all properties of
// student1 object
for (let prop in student1) {
    console.log(prop + " -> "
        + student1[prop]);
}

Output
id -> 123
firstName -> Prakhar
showEnrolledCourses -> function () {
    console.log(courses);
}
firstCourse -> C++ STL
secondCourse -> DSA Self Paced
thirdCourse -> CS Core Subjects

Supported Browsers:

The browsers supported are listed below:

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.


Previous Article
Next Article

Similar Reads

How to loop through HTML elements without using forEach() loop in JavaScript ?
In this article, we will learn how to loop through HTML elements without using the forEach() method. This can be done in the following ways: Table of Content Approach 1: Using the for loopApproach 2: Using the While loopApproach 3: Using the 'for.....of' statementApproach 4: Using the for...in statementApproach 1: Using the for loopThe HTML element
4 min read
How to Loop Through an Array using a foreach Loop in PHP?
Given an array (indexed or associative), the task is to loop through the array using foreach loop. The foreach loop iterates through each array element and performs the operations. PHP foreach LoopThe foreach loop iterates over each key/value pair in an array. This loop is mainly useful for iterating through associative arrays where you need both t
2 min read
How to Change Values in an Array when Doing foreach Loop in JavaScript ?
The forEach loop in JavaScript is one of the several ways to iterate through an array. ForEach method is different from all other looping methods as it passes a callback function for each element in the array. So, the possible approach to change the values in the array when doing foreach method in JavaScript, the method will not directly change the
3 min read
How to break nested for loop using JavaScript?
The break statement, which is used to exit a loop early. A label can be used with a break to control the flow more precisely. A label is simply an identifier followed by a colon(:) that is applied to a statement or a block of code. Note: there should not be any other statement in between a label name and associated loop. Example-1: Break from neste
3 min read
How to trigger setInterval loop immediately using JavaScript ?
This article will show some simple ways in which the setInterval() method can be made to execute the function without delay. There are many procedures to do so, below all the procedures are described with the example. Note: In this article setInterval() method will start immediately for the 1st time run. Below examples illustrate the above approach
2 min read
How to ignore loop in else condition using JavaScript ?
In this article, we will see the methods to ignore the loop in the else conditions using JavaScript. There are two ways to ignore the loop in the else condition: ContinueBreak Please see this, for explanations of the same. In simple terms, The Break statement exits out of the loop while the continue statement exits out of the particular iteration.
2 min read
What are the microtask and macrotask within an event loop in JavaScript ?
Event Loop: An Event Loop in JavaScript is said to be a constantly running process that keeps a tab on the call stack. Its main function is to check whether the call stack is empty or not. If the call stack turns out to be empty, the event loop proceeds to execute all the callbacks waiting in the task queue. Inside the task queue, the tasks are bro
4 min read
JavaScript SyntaxError - A declaration in the head of a for-of loop can't have an initializer
This JavaScript exception a declaration in the head of a for-of loop can't have an initializer occurs if the for -of loop contains an initialization expression like |for (var i = 0 of iterable)|. This is not valid initialization in for-of loops. Message: SyntaxError: for-of loop head declarations cannot have an initializer (Edge) SyntaxError: a dec
1 min read
How to Pause and Play a Loop in JavaScript using Event Listeners ?
Given below is a JavaScript program for DOM manipulation which is basically about How to Pause and Play a loop in JavaScript using event listeners (not to be confused with delay). In this article, we are using JavaScript with HTML so we need a web browser i.e., Chrome (recommended) or Electron Application. Pausing and playing a loop is such a diffi
4 min read
How to delay a loop in JavaScript using async/await with Promise ?
Given below is a JavaScript code snippet which is basically described how to delay a loop in JavaScript using async/await. In this article, we are using JavaScript either the web browser or Node.js. We all face a difficult situation in delaying a loop in JavaScript unlike C++ where we have sleep() function, but there is nothing like this in JavaScr
2 min read
three90RightbarBannerImg