Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator
iteration

What is the for...in loop in JavaScript?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The for...in loop iterates over all the enumerable properties of the object and its inherited objects. If the key is a Symbol, it is ignored.

let user = {name : "Raj", age : 20};
user[Symbol('symbol')] = 'symbol';
console.log("Object is : ", user);
console.log("\nLooping properties with for...in");
for(let key in user) {
console.log(key, user[key]);
}

The above code will print all the properties of the user object because, by default, all properties are enumerable when a property is created by simple assignment or property initializer.

Example with inheritance

let male = {sex: "male"};
// creating a new object from male objecct
let user = Object.create(male);
// adding new properties
user.name = "Ram";
user.age= 20;
for(let key in user) {
console.log(key, user[key]);
}

To list only the current object’s property, use hasOwnProperty().

let male = {sex: "male"};
// creating a new object from male objecct
let user = Object.create(male);
user.name = "Ram";
user.age= 20;
for(let key in user) {
if(user.hasOwnProperty(key)) {
console.log(key, user[key]);
}
}

The above code only prints the properties of the user object because we have added the hasOwnPropertycheck for all the keys.


For more details about for..in click here.

RELATED TAGS

javascript
communitycreator
iteration

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring