DEV Community

Lokesh
Lokesh

Posted on

JavaScript Objects

What Are Objects in JavaScript?

Objects are used to store related information in the form of key-value pairs.

For example, a student has a name, age, and course. Instead of storing these details in separate variables, we can group them into one object.

let student = {
    name: "John",
    age: 22,
    course: "Computer Science"
};
Enter fullscreen mode Exit fullscreen mode

Here, name, age, and course are keys, while "John", 22, and "Computer Science" are their values.

1. Accessing Object Properties

We can access object properties in two common ways.

Dot notation:

console.log(student.name);
Enter fullscreen mode Exit fullscreen mode

Output: John

Bracket notation:

console.log(student["age"]);
Enter fullscreen mode Exit fullscreen mode

Output: 22

Both methods help us access the values stored inside an object.

2. Adding Properties

We can add new properties to an object whenever needed.

student.city = "Chennai";

console.log(student);
Enter fullscreen mode Exit fullscreen mode

This adds a new property called city with the value "Chennai".

3. Updating Properties

We can change the value of an existing property.

student.age = 23;

console.log(student.age);
Enter fullscreen mode Exit fullscreen mode

Output: 23

Here, the student's age changes from 22 to 23.

4. Deleting Properties

We can use the delete operator to remove a property from an object.

delete student.course;

console.log(student);
Enter fullscreen mode Exit fullscreen mode

This removes the course property from the object.

5. Objects with Functions

An object can also contain functions as properties. These functions are commonly called methods.

let person = {
    name: "John",

    greet: function() {
        console.log("Hello!");
    }
};

person.greet();
Enter fullscreen mode Exit fullscreen mode

Output: Hello!

Here, greet() is a method of the person object.

6. Looping Through Objects

We can use a for...in loop to access an object's property names and values.

let product = {
    name: "Laptop",
    price: 50000,
    brand: "HP"
};

for (let key in product) {
    console.log(key, product[key]);
}
Enter fullscreen mode Exit fullscreen mode

This prints each property name along with its value.

Why Are Objects Important?

Objects help us:

  • Store related information together.
  • Organize data clearly.
  • Add, update, and delete properties.
  • Represent real-world things such as students, products, and employees.
  • Create useful applications such as product management systems and shopping carts.

Top comments (0)