In JavaScript, an Object is a collection of properties, where each property is defined as a key-value pair. Objects are one of the fundamental data types and are used extensively in JavaScript.
Defining Objects
You can create an object in several ways:
- Object Literal Syntax:
const person = {
name: "John",
age: 30,
isEmployed: true
};
- Using the
new Object()Syntax:
const person = new Object();
person.name = "John";
person.age = 30;
person.isEmployed = true;
Accessing Object Properties
- Dot Notation: Access properties using the dot
.syntax.
console.log(person.name); // "John"
- Bracket Notation: Access properties using the bracket
[]syntax, which is useful when dealing with dynamic property names or keys that are not valid identifiers.
console.log(person["age"]); // 30
Common Object Methods
JavaScript provides several built-in methods for working with objects. Below are some key methods with examples:
1. Object.keys()
Returns an array of the object’s own enumerable property names (keys).
const person = {
name: "John",
age: 30,
isEmployed: true
};
console.log(Object.keys(person)); // ["name", "age", "isEmployed"]
2. Object.values()
Returns an array of the object’s own enumerable property values.
console.log(Object.values(person)); // ["John", 30, true]
3. Object.entries()
Returns an array of the object’s own enumerable key-value pairs in the form of an array of arrays.
console.log(Object.entries(person));
// [["name", "John"], ["age", 30], ["isEmployed", true]]
4. Object.assign()
Copies the values of all enumerable own properties from one or more source objects to a target object.
const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };
const result = Object.assign(target, source1, source2);
console.log(result); // { a: 1, b: 2, c: 3 }
5. Object.freeze()
Prevents modification (both adding and changing) of an object’s properties.
const frozenObject = Object.freeze({ name: "Alice", age: 25 });
frozenObject.age = 30; // Cannot change; strict mode will throw an error
console.log(frozenObject.age); // 25
6. Object.seal()
Prevents adding or removing properties from an object, but allows modification of existing properties.
const sealedObject = Object.seal({ name: "Alice", age: 25 });
sealedObject.age = 30; // Allowed
delete sealedObject.name; // Not allowed
console.log(sealedObject); // { name: "Alice", age: 30 }
7. Object.create()
Creates a new object, using an existing object as the prototype of the newly created object.
const parent = {
sayHello() {
console.log("Hello!");
}
};
const child = Object.create(parent);
child.sayHello(); // "Hello!"
8. Object.hasOwnProperty()
Returns true if the object has the specified property as its own (not inherited) property.
console.log(person.hasOwnProperty("name")); // true
console.log(person.hasOwnProperty("toString")); // false (inherited from Object prototype)
9. Object.is()
Determines whether two values are the same value (like ===, but handles NaN and -0 cases differently).
console.log(Object.is(25, 25)); // true
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(-0, +0)); // false
10. Object.getOwnPropertyNames()
Returns an array of all properties (enumerable or not) found directly in a given object.
const obj = Object.create({}, {
prop1: { value: 42, enumerable: true },
prop2: { value: 36, enumerable: false }
});
console.log(Object.getOwnPropertyNames(obj)); // ["prop1", "prop2"]
11. Object.defineProperty()
Adds or modifies a property on an object and returns the object.
const person = {};
Object.defineProperty(person, 'name', {
value: 'John',
writable: false, // Cannot be changed
enumerable: true, // Will show up in Object.keys() or for...in loop
configurable: false // Cannot be deleted or modified
});
console.log(person.name); // "John"
person.name = 'Doe'; // Won't change
console.log(person.name); // "John"
12. Object.fromEntries()
Creates an object from an array of key-value pairs (the reverse of Object.entries()).
const entries = [
['name', 'John'],
['age', 30]
];
const person = Object.fromEntries(entries);
console.log(person); // { name: "John", age: 30 }
Example: Combining Object Methods
Here’s a practical example that demonstrates how various object methods work together:
const user = {
name: "Alice",
age: 25,
occupation: "Engineer"
};
// Log object keys
console.log("Keys:", Object.keys(user)); // ["name", "age", "occupation"]
// Log object values
console.log("Values:", Object.values(user)); // ["Alice", 25, "Engineer"]
// Log key-value pairs
console.log("Entries:", Object.entries(user)); // [["name", "Alice"], ["age", 25], ["occupation", "Engineer"]]
// Add new properties by cloning an object
const newUser = Object.assign({}, user, { location: "New York" });
console.log(newUser); // { name: "Alice", age: 25, occupation: "Engineer", location: "New York" }
// Seal the object, preventing adding/removing properties
Object.seal(newUser);
newUser.age = 26; // Allowed
delete newUser.location; // Not allowed (sealed)
console.log(newUser); // { name: "Alice", age: 26, occupation: "Engineer", location: "New York" }
Conclusion
JavaScript objects are powerful and flexible, offering a wide array of methods to create, manipulate, and protect data structures. By mastering these methods, you can handle objects efficiently and use them to structure your application’s data.
