Member-only story
Understanding JavaScript Object’s Keys, Values, and Entries
When and how to use them for beginners
Let’s explore these methods and how to use them daily — Object.keys()
, Object.values()
, and Object.entries() .
An object is a collection of key-value pairs where the keys are strings (or symbols) and the values can be of any data type. Objects are used to store and organize related data.
Example:
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
isStudent: false
};
In this example, person
is an object with four key-value pairs.
Object.keys()
The Object.keys()
method returns an array containing the keys of an object. This is particularly useful when accessing or iterating through an object's keys. Here's how you can use it:
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
isStudent: false
};
const keys = Object.keys(person);
console.log(keys); // ["firstName", "lastName", "age", "isStudent"]
You can use Object.keys()
to loop through the keys and perform operations, like displaying or updating values associated with those keys in your project.