JavaScript Objects

Group related data with key and value pairs, methods and nested objects.

Lesson 26 of 56Beginner13 min read

Arrays are great for lists of similar things. But how do you describe one thing with many details, such as a customer with a name, email and age, or a product with a title, price and stock level? You use an object: a collection of named values.

Objects are everywhere in JavaScript. Data loaded from servers arrives as objects, settings are stored in objects, and the page itself is represented as objects you can change. Once you can create and read objects confidently, most real-world code becomes much easier to follow.

Creating an object

JavaScript
const dog = {
  name: "Biscuit",
  age: 3,
  breed: "Beagle",
  isGoodBoy: true,
};
  • Each entry is a key: value pair, also called a property.
  • Keys are names (strings). Values can be anything: numbers, strings, arrays, other objects or functions.
  • Separate properties with commas. A comma after the last property is allowed and makes adding new lines easier.

Reading and changing properties

  • Dot notation, dog.name, is the usual way to read a property.
  • Bracket notation, dog["name"], is needed when the key is stored in a variable (dog[key]) or contains spaces or hyphens.
  • Add or change properties with dog.age = 4; or dog.owner = "Mia";.
  • Remove a property with delete dog.breed;.
  • Reading a property that doesn't exist gives undefined rather than an error.

Methods and this

A function stored in an object is called a method. Inside a method, this refers to the object the method belongs to:

JavaScript
const dog = {
  name: "Biscuit",
  bark() {
    return `${this.name} says woof!`;
  },
};
dog.bark();

Methods keep data and the actions that use it together. You've already used many built-in methods, such as toUpperCase() on strings and push() on arrays.

Working with all the properties

  • Object.keys(obj) gives an array of the keys.
  • Object.values(obj) gives an array of the values.
  • Object.entries(obj) gives an array of [key, value] pairs.
  • "name" in obj checks whether a key exists.
  • for (const key in obj) loops over the keys.

Converting an object to an array with these helpers lets you use array methods like map and filter on its contents.

Optional chaining with ?.

Reading a property of something that might be missing throws an error: user.address.city crashes if address is undefined. Writing user.address?.city safely returns undefined instead. Combine it with ?? for a default value: user.address?.city ?? "Unknown".

JavaScript Objects Syntax

Object basics

const obj = { key: "value", count: 2 };
obj.key;            // read
obj["count"];       // read with brackets
obj.newKey = true;  // add
delete obj.count;   // remove
Object.keys(obj);   // ["key", "newKey"]
obj.maybe?.deep;    // safe access

JavaScript Objects Summary

  • An object stores named properties as key and value pairs.
  • Read properties with dot notation, or brackets when the key is in a variable.
  • Functions stored in objects are methods, and this refers to the object.
  • Object.keys, Object.values and Object.entries turn objects into arrays.
  • Optional chaining (?.) reads nested properties safely.

JavaScript Objects Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

A user profile

const user = {
  username: "skater_sam",
  followers: 128,
  interests: ["skating", "music"],
  location: { city: "Bristol", country: "UK" },
};

console.log(user.username);
console.log(user["followers"]);
console.log(user.interests[1]);
console.log(user.location.city);

user.followers += 1;
user.verified = true;
console.log(user);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 1 to 6One object holds strings, numbers, an array and a nested object.
  2. Lines 8 to 9Dot and bracket notation do the same thing here.
  3. Line 10Reach into the array.
  4. Line 11Chain dots to reach into a nested object.
  5. Lines 13 to 14Update one property and add a new one.
Example 2

Methods and this

const account = {
  owner: "Lin",
  balance: 50,
  deposit(amount) {
    this.balance += amount;
    return this.balance;
  },
  summary() {
    return `${this.owner} has £${this.balance}`;
  },
};

account.deposit(25);
console.log(account.summary());
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 4 to 7A method; this is the account object.
  2. Lines 8 to 10Methods can read other properties through this.
Example 3

Keys, entries and optional chaining

const stock = { apples: 12, bananas: 0, cherries: 40 };

console.log(Object.keys(stock));
console.log(Object.values(stock));

for (const [fruit, count] of Object.entries(stock)) {
  console.log(`${fruit}: ${count > 0 ? count : "sold out"}`);
}

const field = "cherries";
console.log(stock[field]);

const order = { id: 7 };
console.log(order.delivery?.address ?? "No delivery info");
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 3 to 4Arrays of keys and values.
  2. Lines 6 to 8Loop over [key, value] pairs.
  3. Lines 10 to 11Bracket notation with a variable key.
  4. Line 14?. avoids a crash because delivery doesn't exist; ?? gives a default.

Common JavaScript Objects Mistakes

Dot notation with a variable

Don't
const key = "age";
console.log(person.key); // looks for a property literally called "key"
Do
console.log(person[key]);

Reading deep into missing data

Don't
const city = user.address.city; // TypeError if address is undefined
Do
const city = user.address?.city ?? "Unknown";

Arrow functions as methods using this

Don't
const cat = {
  name: "Tom",
  hi: () => `I'm ${this.name}`, // this isn't the cat
};
Do
const cat = {
  name: "Tom",
  hi() { return `I'm ${this.name}`; },
};

JavaScript Objects in Real Projects

Objects model the real world

Customers, products, messages, settings and game characters are all objects. Data from APIs arrives as objects (written as JSON), and you'll spend a lot of time reading values like response.data.items[0].title.

JavaScript Objects Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Read the city with dot notation, and the country using the variable key.

const place = { city: "Lagos", country: "Nigeria" };
const key = "country";
console.log(place.);
console.log(place[  ]);
Predict the outputeasy

What does this print?

const car = { brand: "Tesla", year: 2022 };
car.year = 2024;
console.log(car.year, car.color);
Multiple choicemedium

Which line safely reads user.profile.avatar when profile might not exist?

Fix the bugmedium

The code should log Mia: 3 pets but crashes and prints the wrong thing. Fix it.

const owner = {
  name: "Mia",
  pets: ["cat", "rabbit", "fish"],
  describe: () => {
    return `${this.name}: ${this.pets.lenght} pets`;
  },
};

console.log(owner.describe());
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Mia: 3 pets"
  • No errors

JavaScript Objects Quiz

3 questions to check what you learned.

  1. What is a property?

    • A function
    • A key and value pair in an object
    • An array index
    • A CSS rule
  2. What does Object.keys({ a: 1, b: 2 }) return?

    • [1, 2]
    • 2
    • { a, b }
    • ["a", "b"]
  3. When must you use bracket notation?

    • When the key is stored in a variable or contains spaces/dashes
    • Always
    • For numbers only
    • Never

JavaScript Objects Challenge

Build a game character

Create an object hero with:

  1. name: "Nova", level: 1, inventory: ["sword"]
  2. A method levelUp() that adds 1 to this.level and returns the new level
  3. A method pickUp(item) that pushes item into this.inventory

Then call hero.levelUp() and hero.pickUp("potion"), and log Nova is level 2 with sword, potion.

ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • hero has the right name
  • levelUp increases the level and returns it
  • pickUp adds an item
  • Logs the summary