DEV Community

Sajin Joe J
Sajin Joe J

Posted on

JavaScript Object

An object in JavaScript is used to store related data and functionality together using key-value pairs.

1. Basic Object

const product = {
    brand: "Samsung",
    price: 25000,
    model: "MHV"
};

console.log(product);
Enter fullscreen mode Exit fullscreen mode
  • brand, price, model → properties
  • "Samsung", 25000, "MHV" → values 2. Change a Property
product.price = 30000;

console.log(product.price);
Enter fullscreen mode Exit fullscreen mode

Output :

30000
Enter fullscreen mode Exit fullscreen mode

3. Add a Property

product.color = "Black";

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

Now the object has

{
    brand: "Samsung",
    price: 30000,
    model: "MHV",
    color: "Black"
}
Enter fullscreen mode Exit fullscreen mode

4. Delete a Property

delete product.color;
Enter fullscreen mode Exit fullscreen mode

5. Nested Object
An object can contain another object.

const product = {
    brand: "Samsung",
    price: 25000,

    port: {
        port1: "HDMI",
        port2: "AUX"
    }
};
Enter fullscreen mode Exit fullscreen mode

Access nested values:

console.log(product.port.port1);
console.log(product.port.port2);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)