for…in object javascript

Hi Guy’s Welcome to Proto Coders Point, In this JS Article let’s under about looking in javascript using for…in loop.

for…in object javascript -How to iterate object in javascript

In Javascript, for…in loop statement is commonly used to iterate object over it’s properties also known a key of an object. This for…in loop is only recommended to used with object not with any array as the behavior might changed during iteration.

Syntax of for…in object loop

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

for…in loop example to iterate object to access it’s properties

const person = {
  firstName: "Rajat",
  lastName: "Palankar",
  age: 20,
  email: "contact@protocoderspoint.com"
};

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

Output

In above code we have an object by name person & I want to iterate it so for that I am using for…in loop to iterate the object over it’s properties.

Each loop it iterate has it’s key property and using that key we can access it’s corresponding value. The output is below:

firstName: Rajat
lastName: Palankar
age: 20
email: contact@protocoderspoint.com

Note: Use for…in loop use only on object, as it misbehave which used with arrays. For iterating an arrays it’s better to use for…of loop or forEach loop.

Similar Articles

convert array into collection

15 useful Javascript Snippets code