D Dev Notebook

JavaScript Objects

JS

JavaScript objects are used to store multiple values in a single variable. They hold data as key-value pairs.

Creating a simple object

let person = {
  name: "John",
  age: 30,
  city: "New York"
};

In this object:

  • name, age, and city are keys (or properties).
  • “John”, 30, and “New York” are values.

Accessing Object Properties

You can access values in two ways:

a. Using dot . notation:

console.log(person.name); // Output: John
console.log(person.age);  // Output: 30

b. Using bracket [] notation:

console.log(person["city"]); // Output: New York

Adding Properties to Objects

You can easily add new properties:

person.job = "Developer";
console.log(person.job); // Output: Developer

Modifying Object Properties

You can update existing properties easily:

person.age = 35; // age was 30, now it becomes 35
console.log(person.age); // Output: 35

Deleting Object Properties

You can delete properties using the delete keyword:

delete person.city;
console.log(person.city); // Output: undefined

Object Methods

Objects can also store functions, known as methods:

let dog = {
  name: "Buddy",
  breed: "Golden Retriever",
  
  bark: function() {
    console.log("Woof! Woof!");
  }
};

dog.bark(); // Output: Woof! Woof!

Looping Through Objects

Use a for...in loop to go through all properties of an object:

for (let key in person) {
  console.log(key + ": " + person[key]);
}

//output
name: John
age: 35
job: Developer

Nested Objects

Objects can contain other objects:

let user = {
  name: "Emma",
  address: {
    street: "123 Main St",
    city: "Boston"
  }
};

console.log(user.address.city); // Output: Boston

Benefits of JavaScript Objects:

  • Store multiple related data easily.
  • Clear and readable code.
  • Easy to add, remove, and update properties.
  • Helps manage complex data.

Objects in JavaScript are containers for data. They store data as key-value pairs, making it easy to group and organize your code clearly and efficiently.

Project

Product Catalog (Shopping App)

Create an interactive product catalog that allows users to browse and view detailed information about products.

Features:

  • Display product information (name, price, description, image URL).
  • Allow users to click and see details.
  • Add search functionality to filter products by name or category.

Project Code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Simple Product Catalog</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f8f8f8;
      margin: 0;
      padding: 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .catalog {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      justify-content: center;
    }

    .product {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      padding: 15px;
      width: 250px;
      cursor: pointer;
      transition: transform 0.3s;
    }

    .product:hover {
      transform: scale(1.05);
    }

    .product img {
      max-width: 100%;
      border-radius: 5px;
      height: 150px;
      object-fit: cover;
    }

    .product h3 {
      margin: 10px 0;
    }

    .product p {
      color: #555;
      font-size: 14px;
    }

    .product .price {
      color: #0c8;
      font-weight: bold;
      margin-top: 10px;
    }

  </style>
</head>
<body>

  <h1>Product Catalog</h1>

  <div class="catalog" id="catalog"></div>

  <script>
    const products = [
      { id: 1, name: "Wireless Mouse", price: 25.99, description: "Comfortable wireless mouse with ergonomic design.", category: "Electronics", image: "https://via.placeholder.com/250?text=Mouse" },
      { id: 2, name: "Bluetooth Headphones", price: 59.99, description: "High-quality sound and noise cancellation.", category: "Electronics", image: "https://via.placeholder.com/250?text=Headphones" },
      { id: 3, name: "Sports Watch", price: 99.99, description: "Durable sports watch with smart features.", category: "Wearable", image: "https://via.placeholder.com/250?text=Watch" },
      { id: 4, name: "Coffee Maker", price: 49.99, description: "Compact coffee maker, perfect for home use.", category: "Home Appliance", image: "https://via.placeholder.com/250?text=Coffee+Maker" }
    ];

    const catalog = document.getElementById('catalog');

    products.forEach(product => {
      const productDiv = document.createElement('div');
      productDiv.classList.add('product');

      productDiv.innerHTML = `
        <img src="${product.image}" alt="${product.name}">
        <h3>${product.name}</h3>
        <p>${product.description}</p>
        <div class="price">$${product.price}</div>
      `;

      productDiv.addEventListener('click', () => {
        alert(`Product: ${product.name}\nPrice: $${product.price}\nCategory: ${product.category}\nDescription: ${product.description}`);
      });

      catalog.appendChild(productDiv);
    });

  </script>

</body>
</html>

Code details:

  • Products are defined using JavaScript objects.
  • Dynamically generates the product list in the browser.
  • Each product shows a brief overview; clicking shows more detailed information.
  • Easily extendable by adding more products to the products array.

On this page