/

Understanding the values() Method of the Object Object

Understanding the values() Method of the Object Object

In JavaScript, the values() method of the Object object is a powerful tool that allows you to easily fetch all the property values of an object. This method returns an array containing all the values of the object’s own properties.

Usage:

To better understand how the values() method works, let’s look at a couple of examples:

Example 1: Retrieving Values from an Object

1
2
const person = { name: 'Fred', age: 87 };
Object.values(person); // Output: ['Fred', 87]

In this example, we have an object called person with two properties: name and age. By using the values() method on the person object, we retrieve an array containing the property values. In this case, the output is ['Fred', 87], which corresponds to the values of the name and age properties.

Example 2: Working with Arrays

1
2
const people = ['Fred', 'Tony'];
Object.values(people); // Output: ['Fred', 'Tony']

The values() method is not limited to objects only; it can also be used with arrays. In this example, we have an array called people with two values: 'Fred' and 'Tony'. By applying the values() method on the people array, we get an array with the same values as the original array. In this case, the output is ['Fred', 'Tony'].

Conclusion

The values() method of the Object object is a convenient way to extract all the property values of an object. It can be used with both objects and arrays, making it versatile in various scenarios. By understanding how to use this method effectively, you can enhance your JavaScript programming skills.

tags: [“JavaScript”, “Object object”, “values() method”]