In JavaScript, the for in
loop is used to iterate over the properties of an object.
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 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];
for (const element of array) {
console.log(element);
}
|
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 = {
firstCourse: "C++ STL" ,
secondCourse: "DSA Self Paced" ,
thirdCourse: "CS Core Subjects"
};
const student1 = Object.create(courses);
student1.id = 123;
student1.firstName = "Prakhar" ;
student1.showEnrolledCourses = function () {
console.log(courses);
}
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 browser supported are listed below:
Last Updated :
11 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...