JavaScript For In: The Complete Guide

0
8
For...in loop in Javascript

Objects created from built-in constructors like Array and Object have inherited non–enumerable properties from the Object.prototype and String.prototype, such as String indexOf method or Object toString method.

Javascript For In

JavaScript For In statement iterates over all non-Symbol, enumerable properties of the Object. The for-in statement loops through the properties of an Object.

Syntax

The syntax of the for…in loop is the following.

for (variable in object) {
 ...
}

Arguments

The variable is a different property name assigned to the variable on each iteration.

The Object is whose non-Symbol enumerable properties are iterated over.

Let’s see the following example.

// app.js

let appObj = { a: 21, b: 22, c: 23 };

for (const prop in appObj) {
  console.log(`appObj.${prop} = ${appObj[prop]}`);
}

We have defined one Object and iterated its properties using for…in statement. 

Output

Javascript For In Loop Tutorial With Example

The for…in loop iterates over the properties of an object in an arbitrary order. If the property is modified in one iteration and then visited at a later time, its value in the loop is its value at that later time.

The property deleted before it has been visited will not be visited later. Properties added to an object over which iteration occurs may either be visited or omitted from iteration.

for…in should not be used to iterate over an Array where the index order is essential.

Array indexes are just enumerable properties with integer names and are otherwise identical to the general object properties. There is no guarantee that the for… statement will return the indexes in any particular order.

The for…in loop statement will return all enumerable properties, including those with the non–integer names and those inherited.

For iterating an array, you can use for loop or forEach function instead.

The for…in statement loops through the properties of the Object.

The code block inside the for…in loop will be executed once for each property.

That’s it for this tutorial.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.