Skip to the content

Lesson 41 of 296

Objects: the basics

What you will learn

  • What an object is
  • Keys and values
  • Dot notation and bracket notation
  • Adding, changing and deleting properties
  • Nested objects and arrays of objects
  • Methods
  • Shorthand syntax
  • Getting the keys and values of an object
On this page

What is an object?

An object groups related data together using names instead of index numbers. Each piece is a key-value pair, also called a property.

const user = {
  name: "Sam",
  age: 30,
  isAdmin: false
};
KeyValue
name"Sam"
age30
isAdminfalse

Use an array for a list of similar things in order. Use an object to describe one thing with named details.

Reading values

Dot notation:

user.name        "Sam"
user.age         30
user.email       undefined (key does not exist)

Bracket notation: the key as a string.

user["name"]     "Sam"

Bracket notation is needed when:

  • the key is stored in a variable:
const field = "age";
user[field];       30
user.field;        undefined  (looks for a key literally called "field")
  • the key has spaces or hyphens: headers["content-type"].

Adding, changing and deleting

user.email = "sam@example.com";    adds a new property
user.age = 31;                     changes a value
delete user.isAdmin;               removes a property

Like arrays, a const object can still be changed inside. const only stops you replacing the whole object.

Checking whether a key exists

"email" in user                 true
user.email !== undefined        true (but fails if the value really is undefined)
Object.hasOwn(user, "email")    true (checks only the object itself)

Nested objects

const order = {
  id: 1042,
  customer: {
    name: "Sam",
    address: {
      city: "Leeds",
      postcode: "LS1 4AP"
    }
  },
  items: ["Kettle", "Toaster"]
};

order.customer.address.city     "Leeds"
order.items[0]                  "Kettle"
order.items.length              2

Arrays of objects

This is the most common data shape you will see from APIs:

const products = [
  { id: 1, name: "Kettle", pricePence: 2999 },
  { id: 2, name: "Toaster", pricePence: 3499 }
];

products[1].name        "Toaster"

Methods

A method is a function stored inside an object.

const calculator = {
  add(a, b) {
    return a + b;
  },
  subtract(a, b) {
    return a - b;
  }
};

calculator.add(2, 3);     5

console.log is also a method: log is a function inside the console object.

Shorthand

If a variable has the same name as the key, write it once:

const name = "Sam";
const age = 30;

const user = { name, age };       same as { name: name, age: age }

Keys, values and entries

const user = { name: "Sam", age: 30 };

Object.keys(user)       ["name", "age"]
Object.values(user)     ["Sam", 30]
Object.entries(user)    [["name", "Sam"], ["age", 30]]

These turn an object into arrays you can loop over (Lesson 42).

Objects are compared and copied by reference

const a = { x: 1 };
const b = a;          b points to the same object
b.x = 99;
console.log(a.x);     99

b = a does not make a copy. To copy:

const copy = { ...a };

This is a shallow copy: nested objects inside are still shared. Part 5 explains shallow and deep copies.

JSON

JSON is a text format for sending data. It looks almost exactly like JavaScript objects, but keys must use double quotes and functions are not allowed.

const text = JSON.stringify(user);       object to JSON text
const back = JSON.parse(text);           JSON text to object

APIs send and receive JSON all the time. Part 5 covers it in more detail.

Common mistakes

  • user.field when the key is in a variable. Use user[field].
  • Reading deep properties when a middle level is missing: order.customer.address.city throws an error if address is undefined. Optional chaining ?. fixes this (Part 5).
  • Thinking b = a copies an object.
  • Missing commas between properties.

How to say it in an interview

"An object stores key-value pairs. I use dot notation normally and bracket notation when the key is dynamic or not a valid identifier. Objects are passed and assigned by reference, so assigning one to another variable does not copy it; the spread operator makes a shallow copy. Object.keys, values and entries turn an object into arrays for looping, and JSON.stringify and JSON.parse convert to and from JSON text."

Key words

WordMeaning
ObjectA collection of named values
PropertyOne key-value pair
KeyThe name of a property
Dot notationuser.name
Bracket notationuser["name"]
MethodA function stored in an object
NestedAn object or array inside another
JSONA text format for data, based on JavaScript object syntax

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.