0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Object.values in JavaScript: Syntax and Examples

Use Object.values(object) to get an array of all the values from the given object. It extracts only the values, ignoring keys, and returns them in the order they appear in the object.
📐

Syntax

The Object.values() method takes a single argument, which is the object you want to extract values from. It returns an array containing all the object's own enumerable property values.

  • object: The object whose values you want to get.
  • Returns: An array of the object's values.
javascript
Object.values(object)
💻

Example

This example shows how to use Object.values() to get all values from a simple object and print them.

javascript
const person = {
  name: 'Alice',
  age: 30,
  city: 'New York'
};

const values = Object.values(person);
console.log(values);
Output
["Alice", 30, "New York"]
⚠️

Common Pitfalls

One common mistake is passing a non-object value to Object.values(), which will cause an error. Also, Object.values() only returns the object's own enumerable properties, so inherited or non-enumerable properties are ignored.

Another pitfall is expecting keys or entries instead of values; for those, use Object.keys() or Object.entries().

javascript
const arr = [1, 2, 3];

// Wrong: passing a non-object (like null) causes error
// Object.values(null); // TypeError

// Correct usage with an object
const obj = {a: 1, b: 2};
console.log(Object.values(obj)); // [1, 2]
Output
[1, 2]
📊

Quick Reference

MethodDescriptionReturns
Object.values(obj)Gets all own enumerable property values of objArray of values
Object.keys(obj)Gets all own enumerable property keys of objArray of keys
Object.entries(obj)Gets all own enumerable key-value pairs of objArray of [key, value] pairs

Key Takeaways

Use Object.values(object) to get an array of all values in the object.
It only includes the object's own enumerable properties, ignoring inherited ones.
Passing non-objects like null or undefined causes errors.
For keys or key-value pairs, use Object.keys() or Object.entries() respectively.
The order of values matches the order of the object's properties.