Complete JavaScript Course Module 7: Intermediate: Objects and JSON

JavaScript Objects Explained: Properties and Methods

  • Beginner
  • Lesson 7.1
  • 5 min read
  • 27 of 76 in the course

In short

A JavaScript object groups related data and actions under one name using key-value pairs. Learn how to create objects, read and change properties, and add methods. What is an object in JavaScript? An array is great for a list of similar things.

A JavaScript object groups related data and actions under one name using key-value pairs. Learn how to create objects, read and change properties, and add methods.

What is an object in JavaScript?

An array is great for a list of similar things. But how do you describe one thing that has many details, like a user with a name, an email and an age? That is what an object is for.

An object is a collection of properties. Each property has a key (its name) and a value. Think of a contact card in your phone: "Name: Ana", "Phone: 555-1234". The labels are keys, and the details are values.

You create an object with curly braces {}. This is called an object literal.

const user = {
  name: "Ana Silva",
  email: "ana@example.com",
  age: 31,
  isAdmin: false,
};

console.log(user);
// Output: { name: "Ana Silva", email: "ana@example.com", age: 31, isAdmin: false }
console.log(user.name);
// Output: Ana Silva

Each property is written as key: value, separated by commas. Values can be any type: strings, numbers, booleans, arrays, or even other objects.

Dot notation vs bracket notation

There are two ways to read a property.

  • Dot notation: user.email. Short and clear. Use it most of the time.
  • Bracket notation: user["email"]. The key is a string inside brackets. You need it when the key is stored in a variable, or when the key has spaces or dashes.
const product = {
  title: "Desk Lamp",
  price: 29,
  "color option": "black",
};

console.log(product.title);           // Output: Desk Lamp
console.log(product["price"]);        // Output: 29
console.log(product["color option"]); // Output: black

const field = "title";
console.log(product[field]);          // Output: Desk Lamp
console.log(product.field);           // Output: undefined
console.log(product.weight);          // Output: undefined

product[field] uses the value of the variable field, which is "title". But product.field looks for a property literally named "field", which does not exist. Reading a missing property gives undefined, not an error.

Common mistake: Using dot notation with a variable, like product.field, when you mean product[field]. Dot notation always uses the exact word you type.

How to add, update and delete properties

Objects can change after you create them, even if you used const (just like arrays). Assign to a new key to add it, assign to an existing key to update it, and use the delete operator to remove it.

const book = { title: "Dune", author: "Frank Herbert" };

book.year = 1965;          // add
book.title = "Dune (Book 1)"; // update
delete book.author;        // remove

console.log(book);
// Output: { title: "Dune (Book 1)", year: 1965 }
console.log("author" in book);
// Output: false

The in operator checks whether an object has a key. It returns true or false.

What are object methods and this?

A property whose value is a function is called a method. Methods are the actions an object can do. You have already used methods: push is a method of arrays.

Inside a method, the keyword this refers to the object the method was called on. It lets the method read the object's own properties.

const account = {
  owner: "Leo",
  balance: 100,
  deposit(amount) {
    this.balance += amount;
    return this.balance;
  },
  describe() {
    return `${this.owner} has $${this.balance}`;
  },
};

account.deposit(50);
console.log(account.describe());
// Output: Leo has $150

deposit(amount) { ... } is the short method syntax. When we call account.deposit(50), this is account, so this.balance grows from 100 to 150.

Note: Do not use arrow functions as object methods when you need this. Arrow functions do not get their own this, so this.balance would not point to the object. Use the short method syntax shown above.

Nested objects, arrays of objects and shorthand properties

Objects can hold other objects and arrays. You read deeper values by chaining dots. An array of objects is one of the most common data shapes in real apps, for example a list of orders from a server.

const order = {
  id: 1042,
  customer: {
    name: "Priya",
    address: { city: "Lisbon", zip: "1100-001" },
  },
  items: [
    { name: "Mug", price: 9 },
    { name: "Coffee beans", price: 14 },
  ],
};

console.log(order.customer.address.city); // Output: Lisbon
console.log(order.items[1].name);         // Output: Coffee beans
console.log(order.items.length);          // Output: 2

Read order.items[1].name left to right: the order, then its items array, then the second item, then its name.

When a variable has the same name as the key you want, you can use shorthand properties. Instead of { name: name }, just write { name }.

const name = "Tom";
const city = "Oslo";

const person = { name, city, country: "Norway" };
console.log(person);
// Output: { name: "Tom", city: "Oslo", country: "Norway" }

Tip: Shorthand properties are very common when building an object from form values or function parameters. They keep code short and avoid repeating yourself.

Practice exercise

Create an object called pet with a name, a species, an age and an array of favoriteToys. Then:

  1. Log the pet's name with dot notation and its species with bracket notation.
  2. Add a new property vaccinated: true and update the age by 1.
  3. Add a method introduce() that returns a sentence like "Hi, I'm Rex, a 4-year-old dog."
  4. Log the second favorite toy.

Hint: Use this.name and this.age inside introduce, and pet.favoriteToys[1] for the toy.

Key takeaways

  • An object stores related data as key-value pairs inside {}.
  • Use dot notation normally and bracket notation for keys in variables or keys with spaces.
  • You can add, update and delete properties, even on a const object.
  • Methods are functions inside objects; this refers to the object the method was called on.
  • Objects can be nested, arrays of objects are everywhere, and { name } is shorthand for { name: name }.

Frequently asked questions

What is the difference between an array and an object?

An array is an ordered list where you find items by number (index). An object stores named details where you find values by key. Use arrays for lists and objects for describing one thing.

Why do I get undefined when reading an object property?

The property does not exist, or the key is spelled differently. Keys are case-sensitive, so user.Name and user.name are different.

Is an array an object in JavaScript?

Technically yes: typeof [] is "object". Arrays are a special kind of object with numbered keys and a length. Use Array.isArray() to tell them apart.