15. JavaScript Objects

What you will learn

  • What an object is and how to create one
  • How to read, add, and change properties
  • How to add methods
  • How to loop over an object and use destructuring

What is an object?

An object groups related data under named properties. Where an array is a list by position, an object is a collection by name. A person, a product, or a lesson are all natural objects.

Creating an object

Example

<p id="demo"></p>

<script>
  const person = {
    firstName: "Sam",
    lastName: "Rivera",
    age: 25,
    skills: ["HTML", "CSS"]
  };

  document.getElementById("demo").textContent =
    person.firstName + " is " + person.age + " years old.";
</script>

Output (after the script runs)

Sam is 25 years old.

Each entry is a key: value pair, separated by commas. Values can be any type, including arrays and other objects.

Reading and changing properties

There are two ways to reach a property:

  • Dot notation: person.age
  • Bracket notation: person["age"]. Use it when the name is stored in a variable or contains spaces.

Example

<p id="demo"></p>

<script>
  const car = { brand: "Toyota", year: 2020 };

  car.year = 2024;            // change
  car.color = "blue";         // add
  delete car.brand;           // remove

  const key = "color";
  document.getElementById("demo").textContent =
    "Year: " + car.year + ", " + key + ": " + car[key] + ", brand: " + car.brand;
</script>

Output (after the script runs)

Year: 2024, color: blue, brand: undefined

As with arrays, a const object can still have its properties changed.

Methods

A property that holds a function is called a method. Inside it, this refers to the object.

Example

<p id="demo"></p>

<script>
  const user = {
    first: "Sam",
    last: "Rivera",
    fullName() {
      return this.first + " " + this.last;
    }
  };

  document.getElementById("demo").textContent = user.fullName();
</script>

Output (after the script runs)

Sam Rivera

Checking and looping

Tool What it gives
"age" in person True if the property exists
Object.keys(obj) An array of the property names
Object.values(obj) An array of the values
Object.entries(obj) An array of [key, value] pairs

Example

<p id="demo"></p>

<script>
  const lesson = { title: "Objects", order: 15, free: true };
  let out = "";

  for (const [key, value] of Object.entries(lesson)) {
    out += key + " = " + value + "<br>";
  }

  document.getElementById("demo").innerHTML = out;
</script>

Output (after the script runs)

title = Objects
order = 15
free = true

Destructuring and spread

Destructuring pulls properties into variables in one line. Spread copies an object.

Example

<p id="demo"></p>

<script>
  const product = { name: "Notebook", price: 4.5, stock: 12 };

  const { name, price } = product;                     // destructure
  const discounted = { ...product, price: 3.5 };       // copy with a change

  document.getElementById("demo").textContent =
    name + " costs " + price + ", sale price " + discounted.price +
    " (original still " + product.price + ")";
</script>

Output (after the script runs)

Notebook costs 4.5, sale price 3.5 (original still 4.5)

Arrays of objects

Real data is often a list of objects, and the array methods from the last lesson work on it.

Example

<p id="demo"></p>

<script>
  const lessons = [
    { title: "HTML", done: true },
    { title: "CSS", done: true },
    { title: "JavaScript", done: false }
  ];

  const todo = lessons.filter((l) => !l.done).map((l) => l.title);
  document.getElementById("demo").textContent = "Still to do: " + todo.join(", ");
</script>

Output (after the script runs)

Still to do: JavaScript

Copying with const b = a does not make a new object. Both names point to the same one. Use { ...a } for a shallow copy. Nested objects inside are still shared.

Common mistakes

  • Using a comma after the last property in older environments, or forgetting commas between properties.
  • Writing obj.key when the name is in a variable. Use obj[key].
  • Reading a missing property and getting undefined, then using it as if it existed.
  • Using an arrow function as a method and losing this.
  • Thinking a copy made with = is independent.

Exercise

Create an object book with the properties title, author, and pages (320), then show the text Title by Author (320 pages) using its values.

Show solution
<p id="demo"></p>

<script>
  const book = {
    title: "Learning Code",
    author: "Sam Rivera",
    pages: 320
  };

  document.getElementById("demo").textContent =
    book.title + " by " + book.author + " (" + book.pages + " pages)";
</script>

Knowledge check

1. What is a function stored in an object called?

A method.

2. When must you use bracket notation?

When the property name is in a variable or contains spaces or special characters.

3. Which syntax makes a shallow copy of an object?

{ ...original }

Summary

  • Objects store data under names, as key: value pairs.
  • Reach properties with dot or bracket notation, and add methods with functions.
  • Use Object.entries, destructuring, and spread to work with objects neatly.
Scroll to Top