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.
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.
let user = {
name: "Liam",
age: 30,
email: "liam@example.com"
};
name
, age
, email
"Liam"
, 30
, "liam@example.com"
Feature | Description |
---|---|
Keys (or Properties) | Must be strings or symbols (no spaces unless quoted) |
Values | Can be any data type — strings, numbers, arrays, even other objects |
Unordered | Object properties don’t follow a guaranteed order |
Arrays | Objects |
---|---|
Ordered list (indexed) | Unordered collection (keyed) |
Use indexes: array[0] | Use keys: object.key |
Best for lists of similar items | Best for describing a single thing |
Scenario | Structure 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" } |
let book = {
title: "JavaScript Basics",
author: "Alex Doe",
pages: 150
};
console.log(book.title); // "JavaScript Basics"
console.log(book["author"]); // "Alex Doe"
name
is the same as "name"
(unless using spaces)