What are the differences between JavaScript's Object.keys() and Object.values()?
Antek N
JavaScript provides two methods,Object.keys() andObject.values(), which allow you to extract information from an object. Here are the differences between these two methods:
1. Returned values:
-Object.keys():
- Returns an array of the object's own enumerable property names (keys).
-Object.values():
- Returns an array of the object's own enumerable property values.
2. Order of returned values:
-Object.keys():
- Returns the property names in the same order as afor...in loop would iterate over the object's properties.
-Object.values():
- Returns the property values in the same order asObject.keys().
3. Usage with arrays and array-like objects:
-Object.keys():
- Can be used with arrays or array-like objects to retrieve their indices.
- For arrays, it returns an array of string indices.
- For array-like objects (e.g., NodeList), it returns an array of indices as strings.
-Object.values():
- Does not work directly with arrays or array-like objects.
- It throws a TypeError if used on an array or array-like object.
4. Handling inherited properties:
-Object.keys() andObject.values():
- Only operate on the object's own enumerable properties and do not include inherited properties.
5. Usage with non-object values:
-Object.keys() andObject.values():
- Throw a TypeError if used on non-object values, such asnull orundefined.
Here's an example illustrating the differences:
In summary,Object.keys() returns an array of property names, whileObject.values() returns an array of property values. The order of returned values is consistent between the two methods, and they both operate on the object's own enumerable properties. However,Object.keys() can also be used with arrays and array-like objects to retrieve their indices, whereasObject.values() does not work directly with them. Remember to handle non-object values appropriately to avoid TypeError exceptions.