DEV Community

Adhi sankar
Adhi sankar

Posted on

Objects in JavaScript

Introduction

Objects are one of the most important features in JavaScript. They allow us to store multiple related values in a single variable using key-value pairs. Objects make it easier to organize and manage data.

What is an Object?

An object is a collection of properties. Each property has a key (name) and a value.

Syntax
let person = {
name: "John",
age: 25,
city: "Chennai"
};
Accessing Object Properties

There are two ways to access object properties.

Dot Notation
console.log(person.name);

Output:

John
Bracket Notation
console.log(person["age"]);

Output:

25
Adding a New Property
person.country = "India";

console.log(person);
Updating a Property
person.age = 26;

console.log(person.age);

Output:

26
Deleting a Property
delete person.city;

console.log(person);
Adding New Properties

You can add new properties at any time.

student.city = "Chennai";

console.log(student);

Output

{
name: "John",
age: 20,
department: "Computer Science",
city: "Chennai"
}
Updating Properties

Modify an existing property by assigning a new value.

student.age = 21;

console.log(student.age);

Output

21
Deleting Properties

Use the delete keyword to remove a property.

delete student.department;

console.log(student);

Output

{
name: "John",
age: 21,
city: "Chennai"
}
Conclusion

Objects are used to store related information in one place. They make JavaScript programs easier to read and maintain. Learning objects is essential because they are widely used in web development and real-world applications.

Top comments (0)