JavaScript Basics: Object.keys, Object.values, and Object.entries

When you call the function Object.keys on an object, it returns an array containing the names of the given object's own, enumerable properties. Contrary to the for...in loop, the inherited properties are not included in the result.

On the other hand, Object.values returns an array containing the values of the given object's own, enumerable properties.

Similarly, Object.entries returns an array which contains the own, enumerable properties of the given object as name and value pairs. Each entry is a two-element array, containing the name and value of a property.

Here is an example:

    let ali = {
        name: "Ali",
        age: 19,
    };

    console.log(Object.keys(ali));    // [ 'name', 'age' ]
    console.log(Object.values(ali));  // [ 'Ali', 19 ]
    console.log(Object.entries(ali)); // [ [ 'name', 'Ali' ], [ 'age', 19 ] ]

In a for...in loop, all the properties in the prototype chain are included in the loop. So if you want to only iterate over own properties, you have to use the hasOwnProperty method or use Object.keys instead.


Related Posts

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center