In JavaScript, an object is an unordered collection of key - value pairs. The keys (also known as properties) are strings, and the values can be of any data type, including numbers, strings, arrays, functions, and even other objects.
Here is a simple example of creating an object:
const person = {
name: 'John',
age: 30,
hobbies: ['reading', 'running']
};
There are two main ways to access object properties: dot notation and bracket notation.
console.log(person.name); // Output: John
console.log(person['age']); // Output: 30
Bracket notation is useful when the property name contains special characters or when the property name is stored in a variable.
You can change the value of an existing property or add a new property to an object.
person.age = 31; // Modify an existing property
person.gender = 'Male'; // Add a new property
console.log(person);
Object.keys()
This method returns an array of an object’s own enumerable property names.
const keys = Object.keys(person);
console.log(keys); // Output: ['name', 'age', 'hobbies', 'gender']
Object.values()
It returns an array of an object’s own enumerable property values.
const values = Object.values(person);
console.log(values);
Object.entries()
This method returns an array of an object’s own enumerable property [key, value]
pairs.
const entries = Object.entries(person);
console.log(entries);
Object.assign()
Used to copy the values of all enumerable own properties from one or more source objects to a target object.
const target = {};
const source = { a: 1, b: 2 };
Object.assign(target, source);
console.log(target); // Output: { a: 1, b: 2 }
Object.freeze()
Prevents new properties from being added to an object, existing properties from being removed, and their values from being changed.
const frozenPerson = Object.freeze(person);
frozenPerson.age = 32; // This will not change the value of age
console.log(frozenPerson.age); // Output: 31
You can use a for...in
loop to iterate over an object’s properties.
for (let property in person) {
console.log(`${property}: ${person[property]}`);
}
Objects can contain other objects, which is useful for representing complex data structures.
const company = {
name: 'ABC Corp',
address: {
street: '123 Main St',
city: 'New York',
state: 'NY'
}
};
console.log(company.address.city); // Output: New York
You can define functions as object properties, which are called methods.
const calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3)); // Output: 8
Use names that clearly describe the purpose of the property. For example, instead of x
, use width
if it represents the width of an element.
Don’t define too many global objects. Instead, encapsulate related functionality within modules or classes.
Before modifying an object, validate the input to prevent unexpected behavior. For example, if you expect a number for an age
property, make sure the input is a valid number.
function updateAge(person, newAge) {
if (typeof newAge === 'number' && newAge > 0) {
person.age = newAge;
} else {
console.error('Invalid age input');
}
}
JavaScript object manipulation is a powerful and essential part of the language. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can effectively use objects to organize data, create complex data structures, and build robust applications. With the right knowledge and techniques, you can take full advantage of JavaScript’s object - oriented capabilities.