JavaScript Object Methods
JavaScript provides powerful built-in Object methods that allow you to work efficiently with object data. These methods help you inspect, modify, clone, and transform objects—essential skills for handling structured data in JavaScript applications.
Here are some commonly used object methods:
- Object.keys(): Returns an array of a given object's property names.
- Object.values(): Returns an array of a given object's property values.
- Object.entries(): Returns an array of a given object's key-value pairs.
- Object.assign(): Copies the values of all enumerable properties from one or more source objects to a target object.
- Object.create(): Creates a new object with the specified prototype object and properties.
- Object.freeze(): Freezes an object, preventing new properties from being added or existing properties from being changed.
- Object.seal(): Seals an object, preventing new properties from being added but allowing existing properties to be modified.
- Object.hasOwn(): Returns a boolean indicating whether the object has the specified property as its own (not inherited).
- Object.getOwnPropertyNames(): Returns an array of all properties (enumerable or not) found directly in a given object.
- Object.getPrototypeOf(): Returns the prototype of the specified object.
- Object.defineProperty(): Defines a new property directly on an object, or modifies an existing one.
Quick Links
- Retrieving Keys and Values (Object.keys, Object.values, Object.entries)
- Cloning and Merging (Object.assign)
- Creating Objects (Object.create)
- Property Inspection (Object.hasOwn, Object.getOwnPropertyNames)
- Prototype Access (Object.getPrototypeOf)
- Property Definition (Object.defineProperty)
- Object Immutability (Object.freeze, Object.seal)
Retrieving Keys and Values from an Object
JavaScript provides built-in methods to extract keys, values, or both from objects. These methods are useful for iterating over object data or transforming it into other formats.
- Object.keys() – Returns an array of a given object's own enumerable property names.
- Object.values() – Returns an array of a given object's own enumerable property values.
- Object.entries() – Returns an array of the object's own enumerable key-value pairs as [key, value] arrays.
Example 1: Using Object.keys() to Get Property Names
The Object.keys() method returns an array of an object's keys. It's often used when you want to loop through property names.
const user = { name: "Tom", age: 25, role: "admin" };
const keys = Object.keys(user);
console.log(keys);
const user = { name: "Tom", age: 25, role: "admin" };
const keys = Object.keys(user);
console.log(keys);
How It Works:
- user: An object with three properties.
- Object.keys(user): Extracts an array of key names.
- console.log(keys): Logs ["name", "age", "role"].
Output
["name", "age", "role"]
["name", "age", "role"]
Example 2: Using Object.values() to Get Property Values
The Object.values() method returns an array of the values of the object’s own enumerable properties.
const user = { name: "Tom", age: 25, role: "admin" };
const values = Object.values(user);
console.log(values);
const user = { name: "Tom", age: 25, role: "admin" };
const values = Object.values(user);
console.log(values);
How It Works:
- Object.values(user): Retrieves all values from the user object.
- Returns them in the same order as the keys.
Output
["Tom", 25, "admin"]
["Tom", 25, "admin"]
Example 3: Using Object.entries() to Get Key-Value Pairs
The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
const user = { name: "Tom", age: 25, role: "admin" };
const entries = Object.entries(user);
console.log(entries);
const user = { name: "Tom", age: 25, role: "admin" };
const entries = Object.entries(user);
console.log(entries);
How It Works:
- Object.entries(user): Converts the object into an array of [key, value] pairs.
- This format is useful for iterating or transforming data.
Output
[["name", "Tom"], ["age", 25], ["role", "admin"]]
[["name", "Tom"], ["age", 25], ["role", "admin"]]
Cloning and Merging Objects
In JavaScript, objects are assigned by reference. To create a true copy or combine multiple objects, you can use the Object.assign() method or the spread operator {...obj}. These tools help you avoid unintentional mutations and merge object properties cleanly.
- Object.assign() – Copies properties from one or more source objects to a target object.
- Spread operator
{...obj}
– A more concise way to clone or merge objects.
Example 1: Cloning an Object with Object.assign()
The Object.assign() method can clone an object by copying its properties into a new empty object.
const original = { name: "Tom", age: 25 };
const clone = Object.assign({}, original);
console.log(clone);
const original = { name: "Tom", age: 25 };
const clone = Object.assign({}, original);
console.log(clone);
How It Works:
- Object.assign({}, original): Creates a shallow copy by assigning properties into a new object.
- clone is a new object, independent from original.
Output
{ name: "Tom", age: 25 }
{ name: "Tom", age: 25 }
Example 2: Merging Multiple Objects with Object.assign()
You can also use Object.assign() to combine multiple objects into one. Properties in later objects overwrite those in earlier ones.
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = Object.assign({}, obj1, obj2);
console.log(merged);
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = Object.assign({}, obj1, obj2);
console.log(merged);
How It Works:
- obj1 and obj2 are merged into a new object.
- b is overwritten by the value from obj2.
- The original obj1 and obj2 are unchanged.
Output
{ a: 1, b: 3, c: 4 }
{ a: 1, b: 3, c: 4 }
Example 3: Cloning with the Spread Operator
The spread operator ... offers a more concise way to clone an object or merge multiple objects.
const original = { name: "Tom", age: 25 };
const clone = { ...original };
console.log(clone);
const original = { name: "Tom", age: 25 };
const clone = { ...original };
console.log(clone);
How It Works:
- { ...original } spreads the properties of original into a new object.
- Just like Object.assign(), this creates a shallow copy.
Output
{ name: "Tom", age: 25 }
{ name: "Tom", age: 25 }
Creating Objects in JavaScript
In JavaScript, Object.create() is used to create a new object.
- Object.create() – Creates a new object with a specified prototype object.
Example 1: Using Object.create()
Object.create() creates a new object with the specified prototype. It's useful when you want to set up inheritance or share methods.
const prototype = {
greet() {
return `Hello, ${this.name}`;
}
};
const user = Object.create(prototype);
user.name = "Tom";
user.age = 30;
console.log(user.greet());
const prototype = {
greet() {
return `Hello, ${this.name}`;
}
};
const user = Object.create(prototype);
user.name = "Tom";
user.age = 30;
console.log(user.greet());
Output
Hello, Tom
Hello, Tom
Property Inspection in JavaScript
JavaScript provides methods to inspect the properties of objects. These can help you determine whether a property exists directly on an object or retrieve all its own property names, including non-enumerable ones.
- Object.hasOwn() – Returns true if the object has the specified property as its own (not inherited).
- Object.getOwnPropertyNames() – Returns an array of all own property names of an object, including non-enumerable properties.
Example 1: Using Object.hasOwn() to Check for a Property
Object.hasOwn() checks if an object has a specific property directly (not through its prototype chain).
const user = { name: "Dana", age: 40 };
console.log(Object.hasOwn(user, "name")); // true
console.log(Object.hasOwn(user, "toString")); // false
const user = { name: "Dana", age: 40 };
console.log(Object.hasOwn(user, "name")); // true
console.log(Object.hasOwn(user, "toString")); // false
How It Works:
- "name" is a direct property of user.
- "toString" is inherited from Object.prototype, so hasOwn returns false.
Output
true
false
true
false
Example 2: Using Object.getOwnPropertyNames() to List All Properties
Object.getOwnPropertyNames() returns an array of all property names directly found on an object, including non-enumerable ones.
const user = Object.create(null);
user.name = "Dana";
Object.defineProperty(user, "role", {
value: "manager",
enumerable: false,
});
console.log(Object.getOwnPropertyNames(user));
const user = Object.create(null);
user.name = "Dana";
Object.defineProperty(user, "role", {
value: "manager",
enumerable: false,
});
console.log(Object.getOwnPropertyNames(user));
How It Works:
- "name" is enumerable by default.
- "role" is non-enumerable but still a direct property.
- getOwnPropertyNames() returns both.
Output
["name", "role"]
["name", "role"]
Prototype Access in JavaScript
JavaScript objects can inherit properties and methods through the prototype chain. The Object.getPrototypeOf() method allows you to access the prototype (i.e., the internal [[Prototype]]) of a given object.
- Object.getPrototypeOf(obj) – Returns the prototype of the specified object. If there is no prototype, it returns null.
Example 1: Accessing the Prototype of an Object
This example shows how to retrieve the prototype of an object created using object literal syntax.
const user = { name: "Sam" };
const proto = Object.getPrototypeOf(user);
console.log(proto);
const user = { name: "Sam" };
const proto = Object.getPrototypeOf(user);
console.log(proto);
How It Works:
- user is created with the object literal syntax.
- Its prototype is Object.prototype, which includes methods like toString.
- Object.getPrototypeOf(user) returns that prototype object.
Output
{ constructor: ƒ, toString: ƒ, hasOwnProperty: ƒ, ... }
{ constructor: ƒ, toString: ƒ, hasOwnProperty: ƒ, ... }
Example 2: Using a Custom Prototype
You can create an object with a specific prototype using Object.create() and then inspect it with Object.getPrototypeOf().
const animal = {
speak() {
return "Generic sound";
}
};
const dog = Object.create(animal);
dog.name = "Buddy";
console.log(Object.getPrototypeOf(dog) === animal);
const animal = {
speak() {
return "Generic sound";
}
};
const dog = Object.create(animal);
dog.name = "Buddy";
console.log(Object.getPrototypeOf(dog) === animal);
How It Works:
- dog is created with animal as its prototype.
- Object.getPrototypeOf(dog) returns the animal object.
- The result is true because they are the same reference.
Output
true
true
Property Definition in JavaScript
JavaScript allows precise control over object properties using Object.defineProperty(). This method lets you define or modify a property with detailed configuration options such as writability, enumerability, and configurability.
- Object.defineProperty(obj, prop, descriptor) – Adds or modifies a property on an object with the given descriptor settings.
Example 1: Defining a Non-Writable Property
In this example, we define a property that cannot be changed after it's set.
const user = {};
Object.defineProperty(user, "role", {
value: "admin",
writable: false,
});
user.role = "editor"; // This won't change the value
console.log(user.role);
const user = {};
Object.defineProperty(user, "role", {
value: "admin",
writable: false,
});
user.role = "editor"; // This won't change the value
console.log(user.role);
How It Works:
- "role" is added to the object with the value "admin".
- Because writable is set to false, the property cannot be reassigned.
- The attempted reassignment is silently ignored in non-strict mode.
Output
admin
admin
Example 2: Making a Property Non-Enumerable
You can use Object.defineProperty() to hide a property from loops and Object.keys().
const user = {};
Object.defineProperty(user, "secret", {
value: "classified",
enumerable: false,
});
console.log(Object.keys(user)); // []
console.log(user.secret); // "classified"
const user = {};
Object.defineProperty(user, "secret", {
value: "classified",
enumerable: false,
});
console.log(Object.keys(user)); // []
console.log(user.secret); // "classified"
How It Works:
- "secret" is defined but not included in enumerations like Object.keys().
- The value can still be accessed directly.
Output
[]
classified
[]
classified
Object Immutability in JavaScript
JavaScript provides methods to control whether objects can be modified. Using Object.freeze() or Object.seal(), you can restrict or lock down objects to prevent accidental changes.
- Object.freeze(obj) – Makes an object immutable: properties cannot be added, removed, or changed.
- Object.seal(obj) – Prevents new properties from being added or existing ones from being removed, but allows modification of existing values (if writable).
Example 1: Using Object.freeze() to Make an Object Fully Immutable
Once an object is frozen, its structure and values cannot be changed.
const user = {
name: "Olivia",
role: "user"
};
Object.freeze(user);
user.role = "admin"; // Will not change
user.age = 30; // Will not be added
delete user.name; // Will not delete
console.log(user);
const user = {
name: "Olivia",
role: "user"
};
Object.freeze(user);
user.role = "admin"; // Will not change
user.age = 30; // Will not be added
delete user.name; // Will not delete
console.log(user);
How It Works:
- Object.freeze(user) locks the object completely.
- All modifications, additions, and deletions are silently ignored (or throw errors in strict mode).
Output
{ name: "Olivia", role: "user" }
{ name: "Olivia", role: "user" }
Example 2: Using Object.seal() to Prevent Structure Changes
Sealing an object allows you to modify existing properties but prevents adding or removing any.
const settings = {
theme: "dark"
};
Object.seal(settings);
settings.theme = "light"; // Allowed
settings.layout = "grid"; // Ignored
delete settings.theme; // Ignored
console.log(settings);
const settings = {
theme: "dark"
};
Object.seal(settings);
settings.theme = "light"; // Allowed
settings.layout = "grid"; // Ignored
delete settings.theme; // Ignored
console.log(settings);
How It Works:
- Object.seal(settings) locks the object's structure but not its values.
- Existing properties can still be updated if they're writable.
- New properties cannot be added, and existing ones cannot be removed.
Output
{ theme: "light" }
{ theme: "light" }
Frequently Asked Questions
What are JavaScript object methods?
What are JavaScript object methods?
JavaScript object methods are functions that are stored as properties of an object and allow you to perform operations related to that object.
How do I use Object.keys()?
How do I use Object.keys()?
Object.keys() returns an array of a given object's own enumerable property names, which can be useful for iterating over the keys.
What does Object.values() do?
What does Object.values() do?
Object.values() returns an array containing the values of all enumerable properties of an object.
When should I use Object.entries()?
When should I use Object.entries()?
Object.entries() is useful when you need both keys and values as an array of [key, value] pairs, often for iteration or transformation.
Can I add custom methods to JavaScript objects?
Can I add custom methods to JavaScript objects?
Yes, you can define your own methods as properties of an object using function expressions or arrow functions.
What’s Next?
Next, you’ll dive into JavaScript Maps—powerful key-value data structures that offer more flexibility than plain objects for managing dynamic data.