Working with Objects
In JavaScript, objects are one of the key constructs for organizing and manipulating data. Objects allow you to group related data and functions together, making it easier to organize and reuse code.
Creating Objects
You can create an object in JavaScript by using the curly braces {}
and defining properties within it. Properties are key-value pairs, where the key is a string (also known as a property name) and the value can be of any type.
1// Define an object representing a person
2const person = {
3 name: 'John',
4 age: 30,
5 hobbies: ['reading', 'running', 'cooking']
6};
In this example, we create an object person
with properties name
, age
, and hobbies
.
Accessing Object Properties
You can access the properties of an object using dot notation (object.property
) or bracket notation (object['property']
).
1console.log(person.name); // Output: John
2console.log(person.age); // Output: 30
3console.log(person.hobbies); // Output: ['reading', 'running', 'cooking']
Modifying Object Properties
You can modify the value of an object property by assigning a new value to it.
1person.age = 35;
2console.log(person.age); // Output: 35
In this example, we modify the age
property of the person
object.
Adding New Properties
You can add new properties to an object by assigning a value to a new key.
1person.location = 'New York';
2console.log(person.location); // Output: New York
In this example, we add a new location
property to the person
object.
Deleting Properties
You can delete a property from an object using the delete
keyword.
1delete person.hobbies;
2console.log(person.hobbies); // Output: undefined
In this example, we delete the hobbies
property from the person
object.
xxxxxxxxxx
// Code example
// Define an object representing a person
const person = {
name: 'John',
age: 30,
hobbies: ['reading', 'running', 'cooking']
};
// Accessing object properties
console.log(person.name); // Output: John
console.log(person.age); // Output: 30
console.log(person.hobbies); // Output: ['reading', 'running', 'cooking']
// Modifying object properties
person.age = 35;
console.log(person.age); // Output: 35
// Adding new properties
person.location = 'New York';
console.log(person.location); // Output: New York
// Deleting properties
delete person.hobbies;
console.log(person.hobbies); // Output: undefined