JavaScript Objects

In JavaScript, an object is a collection of key-value pairs, where each key (or property) has an associated value. Objects allow you to store and organize data, making it easy to manage related data items in a single structure.

Key Features of JavaScript Objects:

Example of Creating a JavaScript Object:

This example demonstrates how to create a basic JavaScript object with properties and access its values:

Example


const person = {
    name: "Alice",
    age: 30,
    greet: function() {
        console.log("Hello, " + this.name);
    }
};

console.log(person.name);    // Alice
person.greet();              // Hello, Alice
             
            

Output

Alice
Hello, Alice

Adding and Modifying Properties:

JavaScript objects are mutable, meaning you can change their properties or add new ones after they are created. Here’s an example:

Example


const car = {
    brand: "Toyota",
    model: "Camry"
    };

    car.year = 2022;               // Add new property
    car.model = "Corolla";         // Modify existing property
    console.log(car);  
    // Output: { brand: "Toyota", model: "Corolla", year: 2022 }

                           

Output

{ brand: "Toyota", model: "Corolla", year: 2022 }

Using Methods in JavaScript Objects:

Methods are functions defined as properties in an object. Here’s an example of an object with a method that performs an action using object properties:

Example


const rectangle = {
    width: 10,
    height: 20,
    area: function() {
        return this.width * this.height;
   }
};

console.log(rectangle.area());  // 200
              
            

Output

200

Deleting Properties from Objects:

You can remove a property from an object using the `delete` operator:

Example


const user = {
    username: "jdoe",
    email: "jdoe@example.com",
    age: 25
};

delete user.age;
console.log(user);  
// Output: { username: "jdoe", email: "jdoe@example.com" }
               
            

Output

{ username: "jdoe", email: "jdoe@example.com" }

When to Use JavaScript Objects:

Objects are ideal when you need to represent data that has multiple properties or characteristics. They are commonly used for storing configurations, managing states, and representing entities in applications, such as users, items, or settings.