Mark As Completed Discussion

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.

JAVASCRIPT
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']).

JAVASCRIPT
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.

JAVASCRIPT
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.

JAVASCRIPT
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.

JAVASCRIPT
1delete person.hobbies;
2console.log(person.hobbies); // Output: undefined

In this example, we delete the hobbies property from the person object.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment