Object methods in JavaScript
Objects are one of the most important data types in JavaScript, and they play a central role in the language. An object is a collection of key-value pairs, where the keys are strings (or symbols), and the values can be any data type, including methods. JavaScript provides a rich set of built-in functions that help you create, manipulate, and interact with objects efficiently. These methods are part of the Object class and offer numerous utilities to handle objects in various ways.
In this article, we will explore the essential object methods in JavaScript, how they work, and how they can help in your day-to-day coding.
1. Object.create(proto, [propertiesObject])
The Object.create()
method creates a new object with a specified prototype object and optional properties. This is a powerful way to set up object inheritance.
Syntax:
Object.create(proto, [propertiesObject])
proto
: The prototype object for the new object.propertiesObject
: An optional parameter to define properties for the new object.
Example:
let animal = {
speak: function() {
console.log("I can speak!");
}
};
let dog = Object.create(animal);
dog.bark = function() {
console.log("Woof!");
};
dog.speak(); // Output: "I can speak!" (inherited from animal)
dog.bark(); // Output: "Woof!"
In this example, the object dog
is created with animal
as its prototype, inheriting the speak
method while adding its own bark
method.
2. Object.assign(target, ...sources)
The Object.assign()
method copies properties from one or more source objects to a target object. This is useful for merging objects or creating shallow copies of objects.
Syntax:
Object.assign(target, ...sources)
target
: The target object to which properties will be assigned.sources
: One or more source objects whose properties will be copied to the target.
Example:
let obj1 = { name: "John", age: 25 };
let obj2 = { age: 30, city: "New York" };
let merged = Object.assign({}, obj1, obj2);
console.log(merged); // Output: { name: "John", age: 30, city: "New York" }
In this case, Object.assign
merges obj1
and obj2
, with the properties of obj2
overwriting those of obj1
if there are conflicts.
3. Object.keys(obj)
The Object.keys()
method returns an array of a given object's own enumerable property names (i.e., keys). It is commonly used to iterate over an object's keys.
Syntax:
Object.keys(obj)
obj
: The object whose keys are to be returned.
Example:
let person = { name: "Alice", age: 25, city: "London" };
console.log(Object.keys(person)); // Output: ["name", "age", "city"]
4. Object.values(obj)
The Object.values()
method returns an array of the object's own enumerable property values. This is useful for iterating over the values stored in an object.
Syntax:
Object.values(obj)
obj
: The object whose property values are to be returned.
Example:
let person = { name: "Alice", age: 25, city: "London" };
console.log(Object.values(person)); // Output: ["Alice", 25, "London"]
5. Object.entries(obj)
The Object.entries()
method returns an array of a given object's own enumerable string-keyed property [key, value]
pairs. It is similar to Object.keys()
but includes both keys and values.
Syntax:
Object.entries(obj)
obj
: The object whose[key, value]
pairs are to be returned.
Example:
let person = { name: "Alice", age: 25, city: "London" };
console.log(Object.entries(person)); // Output: [["name", "Alice"], ["age", 25], ["city", "London"]]
6. Object.freeze(obj)
The Object.freeze()
method freezes an object, making it immutable. Once an object is frozen, you cannot add, remove, or change its properties.
Syntax:
Object.freeze(obj)
obj
: The object to be frozen.
Example:
let car = { brand: "Toyota", model: "Camry" };
Object.freeze(car);
car.model = "Corolla"; // This will not take effect
console.log(car.model); // Output: "Camry"
7. Object.seal(obj)
The Object.seal()
method seals an object, preventing new properties from being added to it. However, existing properties can still be modified.
Syntax:
Object.seal(obj)
obj
: The object to be sealed.
Example:
let user = { name: "Tom", age: 22 };
Object.seal(user);
user.age = 23; // Allowed
user.city = "NY"; // Not allowed (no new properties can be added)
console.log(user); // Output: { name: "Tom", age: 23 }
8. Object.getOwnPropertyNames(obj)
The Object.getOwnPropertyNames()
method returns an array of all properties (enumerable or non-enumerable) found directly on an object, including both string and symbol properties.
Syntax:
Object.getOwnPropertyNames(obj)
obj
: The object whose property names are to be returned.
Example:
let obj = { name: "Alice", age: 25 };
Object.defineProperty(obj, 'hidden', {
value: 'secret',
enumerable: false
});
console.log(Object.getOwnPropertyNames(obj)); // Output: ["name", "age", "hidden"]
9. Object.getPrototypeOf(obj)
The Object.getPrototypeOf()
method returns the prototype (i.e., the internal [[Prototype]]
property) of the specified object. This is useful to check inheritance.
Syntax:
Object.getPrototypeOf(obj)
obj
: The object whose prototype is to be returned.
Example:
let animal = { species: "Mammal" };
let dog = Object.create(animal);
console.log(Object.getPrototypeOf(dog)); // Output: { species: "Mammal" }
10. Object.is(obj1, obj2)
The Object.is()
method compares two values to determine if they are the same. It is similar to the strict equality operator (===
), but it also correctly handles edge cases like NaN
.
Syntax:
Object.is(obj1, obj2)
obj1
,obj2
: The two objects or values to be compared.
Example:
console.log(Object.is(25, 25)); // Output: true
console.log(Object.is(NaN, NaN)); // Output: true (unlike `===` which returns false)
console.log(Object.is(0, -0)); // Output: false
11. Object.defineProperty(obj, prop, descriptor)
The Object.defineProperty()
method allows you to define a new property on an object or modify an existing one with specific property descriptors (e.g., writable
, enumerable
, configurable
).
Syntax:
Object.defineProperty(obj, prop, descriptor)
obj
: The object on which to define or modify the property.prop
: The property name to define or modify.descriptor
: An object that describes the property.
Example:
let person = { name: "John" };
Object.defineProperty(person, "age", {
value: 30,
writable: false
});
person.age = 25; // This will not change the value
console.log(person.age); // Output: 30
12. Object.defineProperties(obj, props)
The Object.defineProperties()
method defines multiple properties at once on an object.
Syntax:
Object.defineProperties(obj, props)
obj
: The object on which to define or modify properties.props
: An object containing one or more property descriptors.
Example:
let person = {};
Object.defineProperties(person, {
name: {
value: "Alice",
writable: true
},
age: {
value: 25,
writable: false
}
});
console.log(person.name); // Output: "Alice"
console.log(person.age); // Output: 25
JavaScript provides a wide array of powerful built-in object functions that make it easier to work with objects in a more flexible and efficient way. Functions like Object.create()
, Object.assign()
, and Object.freeze()
are invaluable for object manipulation, while methods like Object.keys()
, Object.values()
, and Object.entries()
help in iterating over objects. Understanding and using these functions will allow you to write more effective