Skip to main content

🎒 Objects

A backpack with labeled pockets

The Backpack Analogy

Think about a well-organized backpack:

  • Laptop goes in the laptop pocket
  • Water bottle goes in the side pocket
  • Keys go in the front zipper pocket
  • Snacks go in the top compartment

Each pocket has a label (laptop, water, keys) and contains something (the actual item).

Objects work exactly the same way.

An object is a container with labeled compartments. Each label is called a key, and what's inside is called a value.

Object: person
├── name: "Alice"      ← key: value
├── age: 30            ← key: value
├── city: "Sydney"     ← key: value

Instead of three separate variables, everything about this person is in ONE organized container!


Why Objects Matter

The Problem: Too Many Related Variables

Without objects, describing a person requires separate variables:

person1_name = "Alice"
person1_age = 30
person1_city = "Sydney"
person1_email = "alice@example.com"

person2_name = "Bob"
person2_age = 25
person2_city = "Melbourne"
person2_email = "bob@example.com"

Problems:

  • 4 separate variables per person
  • Easy to lose track of what belongs together
  • Passing to functions? You'd need 4 parameters!

With Objects:

person1 = { name: "Alice", age: 30, city: "Sydney", email: "alice@..." }
person2 = { name: "Bob", age: 25, city: "Melbourne", email: "bob@..." }

One variable contains everything. Pass it to a function? Just pass ONE thing.


How Objects Work

Creating an Object:

Objects use curly braces {} with key-value pairs:

const person = {
  name: "Alice", // key: value
  age: 30, // key: value
  city: "Sydney", // key: value
};

Accessing Values:

Use dot notation to get values:

person.name   → "Alice"
person.age    → 30
person.city   → "Sydney"

Updating Values:

person.age = 31          // Change existing value
person.country = "AU"    // Add new key-value pair

Real-World Examples

1. User Profile (What You See on Every Website)

user = {
  username: "alice_dev"
  email: "alice@example.com"
  avatar: "/images/alice.jpg"
  isVerified: true
  joinDate: "YYYY-MM-DD"
}

2. Product in Shopping Cart

product = {
  id: "SKU-001"
  name: "Wireless Headphones"
  price: priceAmount
  quantity: 2
  inStock: true
}

3. API Response (Everything from the Internet)

weatherData = {
  location: "Sydney"
  temperature: 24
  condition: "Sunny"
  humidity: 65
}

4. Game Character

player = {
  name: "Hero"
  health: 100
  level: 5
  position: { x: 100, y: 200 }
  inventory: ["sword", "shield", "potion"]
}

Notice: Objects can contain other objects (nested) and arrays!


Objects Can Have Actions (Methods)

Objects don't just store data - they can also do things!

A method is a function inside an object:

calculator = {
  add: function(a, b) { return a + b }
  subtract: function(a, b) { return a - b }
}

calculator.add(5, 3)      → 8
calculator.subtract(10, 4) → 6

Real example:

bankAccount = {
  balance: 1000
  deposit: function(amount) { this.balance += amount }
  withdraw: function(amount) { this.balance -= amount }
}

bankAccount.deposit(500)   → balance is now 1500
bankAccount.withdraw(200)  → balance is now 1300

The this keyword refers to "this object itself."


Nested Objects (Objects Inside Objects)

Objects can contain other objects:

company = {
  name: "Tech Corp"
  address: {
    street: "123 Main St"
    city: "Sydney"
    country: "Australia"
  }
  ceo: {
    name: "Alice Smith"
    age: 45
  }
}

company.address.city   → "Sydney"
company.ceo.name       → "Alice Smith"

This is how real data is organized - hierarchically!


Objects vs Arrays: When to Use Which

Use Object WhenUse Array When
Data has names/labelsData is a list
You look up by nameOrder matters
Representing ONE thingRepresenting MANY things
"What is the user's email?""What's the 3rd item?"

Example:

// Object: ONE user with properties
user = { name: "Alice", age: 30, email: "alice@..." }

// Array: MANY users in a list
users = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Carol", age: 35 }
]

Common Mistakes

Mistake 1: Copying Objects Incorrectly

When you assign an object to another variable, you don't copy it - you create a reference to the SAME object:

original = { name: "Alice" }
copy = original           ← NOT a copy! Same object!

copy.name = "Bob"
original.name             → "Bob" (changed!)

To actually copy:

realCopy = { ...original }  ← Spread operator makes a copy

Mistake 2: Checking If Property Exists Incorrectly

user = { name: "Alice", age: 0 }

// ❌ Wrong - 0 is "falsy" so this fails!
if (user.age) { ... }

// ✓ Correct - check if key exists
if ("age" in user) { ... }

Mistake 3: Wrong Notation for Special Keys

data = { "first-name": "Alice" }

// ❌ Dot notation fails for keys with hyphens
data.first-name   → Error!

// ✓ Bracket notation works
data["first-name"] → "Alice"

FAQ

Q: How do I loop through an object?

Use for...in to loop through keys, or Object.entries() for key-value pairs:

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

Q: How do I check if an object is empty?

const isEmpty = Object.keys(obj).length === 0;

Q: What's the difference between null and undefined in objects?

  • undefined: The property doesn't exist or wasn't assigned
  • null: The property exists but intentionally has no value

Q: Can object keys be anything?

In JavaScript, object property keys are strings or Symbols. If you use a number as a key, it will be converted to a string.

Q: How do I merge two objects?

Use the spread operator:

const merged = { ...object1, ...object2 };

Q: What is destructuring?

A shorthand to extract properties:

const { name, age } = person; // Creates variables name and age

Summary

Objects let you group related data together in one organized container. They're fundamental to JavaScript - everything from DOM elements to API responses uses objects.

Key Takeaways:

  • Objects store key-value pairs (like labeled compartments)
  • Access values with dot notation: object.key
  • Objects can contain functions (methods) and other objects
  • Assigning objects creates references, not copies
  • Use {...obj} to make a shallow copy
  • Use "key" in object to check if a key exists
  • Objects for named properties, arrays for ordered lists

Master objects and you can work with almost any JavaScript code!

Leave a Comment

Comments (0)

Be the first to comment on this concept.

Comments are approved automatically.