๐ŸŽฏ

JavaScript Objects

Work with structured data using properties and methods

โญ Core Concept

What are Objects?

Objects store collections of key-value pairs. Think of a recipe card: it has a name, ingredients list, cooking time, difficulty level - each piece of information has a label (key) and value!

๐Ÿ’ก Real-World Example:

A dish object: { name: "Pizza", price: 12.99, rating: 4.5, ingredients: ["cheese", "tomato"] }

Working with Objects

1. Creating Objects

const dish = {
    name: "Pasta Carbonara",
    price: 15.99,
    servings: 2,
    isVegetarian: false
};

2. Accessing Properties

console.log(dish.name);        // "Pasta Carbonara" (dot notation)
console.log(dish["price"]);    // 15.99 (bracket notation)

3. Modifying Properties

dish.price = 17.99;           // Update existing
dish.chef = "Mario";          // Add new property
delete dish.servings;         // Remove property

4. Object Methods

const recipe = {
    name: "Cake",
    bake: function() {
        return `Baking ${this.name}!`;
    }
};
console.log(recipe.bake()); // "Baking Cake!"

5. Object.keys(), Object.values()

const menu = { pasta: 12, pizza: 15, salad: 8 };
console.log(Object.keys(menu));    // ["pasta", "pizza", "salad"]
console.log(Object.values(menu));  // [12, 15, 8]

Learn More

๐Ÿš€ Try It Yourself

Output:

๐Ÿฝ๏ธ

Game 1: Build Your Dish

Create custom dishes by building object structures! Practice adding properties, nested objects, and methods.

๐Ÿ› ๏ธ Dish Builder

๐Ÿ“ฆ Generated Object

๐Ÿ“‹ Your Menu (0 dishes)

๐Ÿ‘ค

Game 2: Customer Profile Manager

Manage customer profiles with nested objects! Track orders, preferences, and loyalty points.

๐Ÿ‘ฅ Customers

๐Ÿ“Š Customer Details

Select a customer to view details
๐Ÿ•

Challenge 1: Build Your Dish

๐Ÿ“‹ Your Mission:

Create a dish object with calculated properties:

  1. Create an object with name, basePrice, and toppings (array)
  2. Add a totalPrice property (basePrice + 2 per topping)
  3. Add a description method that returns a summary string

Example:

createDish("Pizza", 10, ["cheese", "pepperoni"])

โ†’ { name: "Pizza", totalPrice: 14, description: "Pizza with 2 toppings" }

๐Ÿ’ก Hints:

  • Calculate totalPrice using toppings.length
  • Return an object with name, totalPrice, and description properties
  • Description should be a string, not a function

Test Results:

๐Ÿ‘ค

Challenge 2: Customer Profile Manager

๐Ÿ“‹ Your Mission:

Update a customer object and add new properties:

  1. Add a new order to the customer's orders array
  2. Update the totalSpent by adding the order amount
  3. Add a loyaltyLevel property ("bronze" if totalSpent < 100, "silver" if < 200, else "gold")

Example:

updateCustomer({ name: "Alice", orders: [], totalSpent: 50 }, 75)

โ†’ { ..., orders: [75], totalSpent: 125, loyaltyLevel: "silver" }

๐Ÿ’ก Hints:

  • Make a copy with {...customer} (spread)
  • Use [...customer.orders, newOrder] for orders
  • Use if/else for loyaltyLevel logic

Test Results: