Lesson 5: Introduction to Objects

Lesson Goal:

Understand what objects are in JavaScript, how to define them using key-value pairs, and how they differ from arrays. Objects are essential for modeling real-world data.


What is an Object?

In JavaScript, an object is a data structure used to store related data as key-value pairs.

Think of an object as a way to describe something with named properties. It’s like a labeled box where each label (key) has a corresponding value.


Object Syntax

let user = {
  name: "Liam",
  age: 30,
  email: "liam@example.com"
};
  • Keys: name, age, email
  • Values: "Liam", 30, "liam@example.com"
  • Each key-value pair is separated by a comma

Key Characteristics

FeatureDescription
Keys (or Properties)Must be strings or symbols (no spaces unless quoted)
ValuesCan be any data type — strings, numbers, arrays, even other objects
UnorderedObject properties don’t follow a guaranteed order

Arrays vs. Objects

ArraysObjects
Ordered list (indexed)Unordered collection (keyed)
Use indexes: array[0]Use keys: object.key
Best for lists of similar itemsBest for describing a single thing

Real-World Examples

ScenarioStructure Example
A user profile{ name: "Emma", age: 25, isMember: true }
A product{ id: 101, title: "Book", price: 9.99 }
A contact card{ name: "Ali", phone: "123-456-7890", email: "ali@mail.com" }

Try It Yourself

let book = {
  title: "JavaScript Basics",
  author: "Alex Doe",
  pages: 150
};

console.log(book.title);      // "JavaScript Basics"
console.log(book["author"]);  // "Alex Doe"

Tips for Beginners

  • Strings as keys can be quoted or unquoted: name is the same as "name" (unless using spaces)
  • Values can be any data type, including arrays or nested objects
  • Objects are mutable — you can add, change, or delete properties later

Summary

  • Use arrays to store lists of items
  • Use objects to describe entities with multiple attributes
  • Objects are used everywhere: APIs, DOM elements, app configurations, and more