![]() |
The for…in and Object.keys() in JavaScript are used to iterate over the properties of an object. While they might seem similar at first glance they have distinct usage, behavior, and characteristics. This article will explore these differences in detail. These are the following topics that we are going to discuss: What is for…in?The for…in statement is a looping construct that iterates over the enumerable properties of an object. It goes through each property name (key) in the object and allows to perform the actions with these properties. Characteristics:
Applications:
Example: In this example, the for…in loop iterates over the properties name and age of the person object as well as the gender property inherited from the Object.prototype.
Output name: kumar age: 25 gender: Male What is Object.keys()?The Object.keys() method returns an array of the given object’s own enumerable property names in the same order as provided by the for…in loop but without including the properties from the prototype chain. Characteristics:
Applications:
Example: In this example Object.keys(person) returns an array containing only the name and age properties excluding the inherited gender property.
Output [ 'name', 'age' ] name: kumar age: 30 Difference Between for…in and Object.keys()
ConclusionUnderstanding the differences between the for…in and Object.keys() is crucial for effectively working with the objects in JavaScript. While for…in is useful for the iterating over all enumerable properties Object.keys() provides a cleaner approach for retrieving only an object’s own properties. Choosing the right method depends on the specific use case and the properties we need to the work with. |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 18 |