Loading

T4 JavaScript · Lesson 7

Objects

Keeping the facts about one thing together: making and reading objects, adding, changing and deleting properties, why two names can share one object and how to copy one, methods and this, getters and setters, looping over an object, arrays of objects, nested objects and JSON.

  • make an object, and read its properties with a dot or with square brackets
  • add, change and delete properties, and say what const does and does not protect
  • say when two names share one object, and make a shallow or a deep copy
  • write methods that use this, make many similar objects with a factory function, and use getters and setters
  • loop over an object's properties, and work with arrays of objects
  • read nested objects safely, and turn objects into JSON text and back
About 75 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-06)Play this lesson's games

The back cover

A student is not one value. There is a name, a roll number, a class, marks in five subjects and a phone number for the parents. Keeping each in its own variable soon becomes a mess. An object keeps all the facts about one thing together, each under a label.

These pages show how to make an object and read it, and how to add, change and delete its properties. They explain why two names can share one object and how to copy one. They show methods and this, how to loop over an object and work on arrays of objects, and JSON, objects written as text.

Before you start

The story: Four lists out of step

The lamplighter's clockwork now keeps notes on every lamp: its number, its street, how much oil it holds, and when it was last lit. Each kind of note is in a list of its own, four lists side by side. On Monday the lamp outside the fish market was taken down, and someone struck it off the list of streets, and off no other list.

Since then, every lamp past the fish market has been filled for the wrong street, and the clockwork sends oil each night to a lamp that is not there.

Master Hakim Verge lays the four lists side by side. "Four lists that must keep in step will one day fall out of step," he says. "Keep each lamp's notes together."

An array is good for many things of one kind, in order. But most things in a program have several facts about them, of different kinds: a student has a name, a roll number and marks; a lamp has a number, a street and its oil. Keeping each kind of fact in a separate list works until the lists fall out of step. An object keeps all the facts about one thing together, each under a label.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Arrays.["Asha", 42]An object labels its values instead of numbering them.
typeof.typeof [] gives object.Arrays are one kind of object.
References.const b = a; shares an array.Objects are shared the same way.
Copying with slice.a.slice()Objects have their own ways to copy.
const.A const array can change inside.So can a const object.
Functions.function greet(name) { ... }A function kept in an object is a method.
Arrow functions.(n) => n * 2They treat this differently.
Optional chaining.user?.nameReading deep inside objects safely.
for...in.Gives names, not items.It was made for objects.
map, filter, reduce.prices.map((p) => p * 2)Arrays of objects use them all the time.

By the end of this lesson you will be able to:

  • make an object, and read its properties with a dot or with square brackets;
  • add, change and delete properties, and say what const does and does not protect;
  • say when two names share one object, and make a shallow or a deep copy;
  • write methods that use this, make many similar objects with a factory function, and use getters and setters;
  • loop over an object's properties, and work with arrays of objects;
  • read nested objects safely, and turn objects into JSON text and back.

How to follow this lesson

Every block on this page runs. console.log prints an object in braces, each property as its name, a colon and its value. When an object is not what you expect, print it whole, and compare the names you see with the names your code uses. Most slips in this lesson are a name spelt one way in one place and another way in another.

In one line

An object keeps the facts about one thing together, each value under its own name.

Making an object, and reading it

At a glance

A school's admission form has labelled boxes: name, roll number, class, phone. Each box holds one fact, and the label says which. An object is that form in code: properties, each a key and a value, written in braces.

Read a property with a dot, or with brackets when the key is kept in a name or has a space. A missing property gives undefined, not an error. To ask whether a key exists at all, write "key" in obj.

Take a guess: What does an object give back for a property it does not have?

A school's admission form has labelled boxes: Name, Roll number, Passed. Each box holds one fact, and the label says what the fact is. An object is that form, in code.

Object

A value that holds named values, written between braces: { name: "Asha", roll: 42 }. Each named value is a property; its name is the key, and what it holds is the value.

const student = { name: "Asha", roll: 42, passed: true };
console.log(student, student.name, student.roll, typeof student);
{ name: 'Asha', roll: 42, passed: true } Asha 42 object

Read the braces as "name is Asha, roll is 42, passed is true". Each property is a key, a colon and a value, with commas between the properties. The values can be of any type, objects and arrays included. console.log prints the whole object in the same shape, with strings in single quotes.

Reading a property

There are two ways to read a property. Dot notation, student.name, read aloud as "student's name", is the usual one. Bracket notation, student["name"], puts the key in square brackets as a string. They give the same value:

const student = { name: "Asha", roll: 42 };
console.log(student.city, student["name"], "roll" in student, "city" in student);
undefined Asha true false

Reading a property that does not exist gives undefined, with no error, as student.city shows. To ask whether a property is there at all, use the in operator: "roll" in student is true. Asking with in is safer than testing for undefined, because a property can exist and hold undefined.

When the key is in a name

Bracket notation is needed when the key is not written in the code but held in a name, for example a key chosen by the user. Inside brackets, the name is worked out first:

const key = "roll";
const student = { name: "Asha", roll: 42 };
console.log(student[key], student.key);
42 undefined

student[key] uses the value of key, which is "roll", so it reads the roll. student.key asks for a property whose name is the word key itself, which does not exist.

Names for properties

A key that follows the rules for names, such as roll or passedExam, can be written bare. A key with a space or a hyphen in it must be written in quotes, and read with brackets:

const item = { "item name": "chai", "price-in-rupees": 15 };
console.log(item["item name"], item["price-in-rupees"]);
chai 15
const item = { price-in-rupees: 15 };
Uncaught SyntaxError: Unexpected token '-'

Every key is a string in the end. Numbers and booleans used as keys are turned into strings:

const box = { 1: "one", true: "yes" };
console.log(box["1"], box[1], Object.keys(box));
one one [ '1', 'true' ]

Most code keeps to keys written in camelCase, like the names of the values lesson, so that the dot always works.

Worked example 1

A railway reservation has a passenger's name, age, coach and berth. Make an object for Asha Rao, 34, in coach B2, berth 17, and print a line such as Asha Rao (34): B2/17.

What we have: four facts about one passenger

What we need: one object, and a line built from its properties

The plan: make the object with four properties, then read each with a dot inside a template literal

const passenger = { name: "Asha Rao", age: 34, coach: "B2", berth: 17 };
console.log(`${passenger.name} (${passenger.age}): ${passenger.coach}/${passenger.berth}`);
Asha Rao (34): B2/17

It prints Asha Rao (34): B2/17.

Check: every part of the line comes from a property of the one object, so the facts cannot drift apart.

A path that fails: keeping four arrays, names, ages, coaches and berths, with Asha at index 0 in each. It works until one array loses an item and the others do not, as the lamplighter's four lists did.

Worked example 2

A results portal lets a teacher choose a subject from a list, and must show that subject's mark. The marks are maths 88, science 92 and english 79, and the teacher chose science. Read the mark.

What we have: an object of marks, and the chosen subject held in a name

What we need: the mark for the chosen subject

The plan: the key is in a name, so read it with square brackets

const marks = { maths: 88, science: 92, english: 79 };
const chosen = "science";
console.log(marks[chosen], chosen in marks);
92 true

The mark is 92.

Check: marks.science gives the same 92, but only bracket notation works when the subject is chosen while the program runs.

A path that fails: writing marks.chosen. It looks for a subject literally called chosen, and gives undefined.

When you are stuck: a property comes out as undefined

Print the whole object and compare the key you see with the key you used, letter by letter and capital by capital.

If the key is held in a name, use brackets: obj[key], not obj.key.

Ask "key" in obj to tell a missing property from one that holds undefined.

A key with a space or a hyphen must be quoted, and read with brackets.

Your turn

const phone = { brand: "Lava", price: 9999 };
console.log(phone.brand, phone["price"], phone.colour);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Lava 9999 undefined
  1. phone.brand is Lava.
  2. phone["price"] is the same as phone.price: 9999.
  3. There is no colour property: undefined.

It prints Lava 9999 undefined.

When must you use obj[key] rather than obj.key?Tap to reveal
  1. When the key is held in a name, such as a choice made while the program runs.
  2. When the key is not a valid name, such as one with a space or a hyphen.

When the key is in a name, or not a valid name.

Make an object for a book with the title Panchatantra and the price 250, and print its title.Tap to reveal
const book = { title: "Panchatantra", price: 250 };
console.log(book.title);
Panchatantra

book.title is Panchatantra.

Did you know?

Numbers first, then the rest

An object's keys come back in an order the standard fixes. Keys that look like array indexes come first, in ascending numeric order; the other string keys follow in the order they were created. So an object made as { b: 1, 2: 1, a: 1, 1: 1 } lists its keys as 1, 2, b, a. Order of writing is kept only for ordinary names.

Why it fits here: It explains a surprise when this topic's objects are printed: number-like keys jump to the front, in number order.

Source: ECMAScript Language Specification: OrdinaryOwnPropertyKeys

Every key is text

An object's keys are always text, or symbols. MDN puts it plainly: the keys of an Object must be either a String or a Symbol, while a Map's keys can be any value. So obj[1] and obj["1"] read the very same property: the number is turned into the string "1" first. The standard's ToPropertyKey step does that turning.

Why it fits here: It explains this topic's brackets: whatever goes inside them becomes a text key, so 1 and "1" name one property.

Sources: MDN: Map; ECMAScript Language Specification: ToPropertyKey

In one line

An object holds properties, each a key and a value, in braces. Read one with a dot, or with brackets when the key is in a name or has a space; a missing property gives undefined, and "key" in obj asks whether it exists.

Adding, changing and deleting properties

At a glance

A student's record changes over the year: a new phone number, a class moved up, a nickname added and later removed. Objects change in the same ways, by assigning and deleting.

Assigning to a property adds it or changes it, and delete removes it. A const object can still change inside, but the name cannot hold a different object. And { name, roll } is shorthand for { name: name, roll: roll }, when the names already exist. None of these steps makes a new object; the same object changes in place.

Take a guess: Can a property be added to an object declared with const?

A form can be filled in later, corrected, or have a box crossed out. Objects are mutable, like arrays: their properties can be added, changed and removed after the object is made.

const student = { name: "Asha" };
student.roll = 42;
student.name = "Asha Rao";
delete student.roll;
console.log(student);
{ name: 'Asha Rao' }

Assigning to a property that does not exist adds it: roll is added. Assigning to one that exists changes it: name becomes Asha Rao. The delete operator removes a property, key and value both. After the three changes, only name is left.

Setting a property to undefined is not the same as deleting it. The property is still there, holding undefined, and in still finds it. Use delete when the property should be gone.

const and objects

As with arrays, const promises only that the name keeps the same object. The object's properties can still change, but the name cannot be given a different object:

const settings = { theme: "dark" };
settings.theme = "light";
console.log(settings);
{ theme: 'light' }
const settings = { theme: "dark" };
settings = { theme: "light" };
Uncaught TypeError: Assignment to constant variable.
    at line 2

So most objects are made with const, like most arrays: the name always means this one object, and the object can still be kept up to date.

A shortcut: shorthand properties

Very often a property takes its value from a name of the same spelling: { name: name, roll: roll }. JavaScript lets you write the name once, and fills in the rest. This is called a shorthand property:

const name = "Asha";
const roll = 42;
const student = { name, roll };
console.log(student);
{ name: 'Asha', roll: 42 }

Worked example 3

A UPI app keeps a payment as an object. It is made with an amount of ₹250 and the status pending. When the bank replies, the status becomes paid and a reference number, 6141, is added; a temporary note that was added at the start is then removed. Show the payment after each change.

What we have: a payment object, and three changes

What we need: the object after the bank's reply

The plan: change status, add the reference, delete the note, then print

const payment = { amount: 250, status: "pending", note: "waiting for bank" };
payment.status = "paid";
payment.reference = 6141;
delete payment.note;
console.log(payment);
{ amount: 250, status: 'paid', reference: 6141 }

The payment is { amount: 250, status: 'paid', reference: 6141 }.

Check: the note is gone, so "note" in payment would now be false.

A path that fails: setting payment.note = undefined to remove the note. The key is still there, and a screen that lists every property would show a note with nothing in it.

When you are stuck: a property will not change, or comes back

Check the spelling of the key: student.Name = ... adds a new property called Name, and leaves name alone.

To remove a property, use delete; setting it to undefined leaves the key in place.

If the name itself must hold a different object, make it with let, not const.

Print the object just before and just after the change.

Your turn

const cup = { size: "small" };
cup.size = "large";
cup.price = 40;
console.log(cup);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
{ size: 'large', price: 40 }
  1. size is changed to large.
  2. price is added, as it did not exist.

It prints { size: 'large', price: 40 }.

What does const o = { a: 1 }; o.A = 2; console.log(o); print, and why?Tap to reveal
  1. Keys are case-sensitive, like names.
  2. o.A is a different key from o.a, so it is added.

{ a: 1, A: 2 }: a second property was added.

Write the object { city: city, pin: pin } with shorthand properties, for city Pune and pin 411001.Tap to reveal
const city = "Pune";
const pin = "411001";
console.log({ city, pin });
{ city: 'Pune', pin: '411001' }

{ city, pin }.

Did you know?

A safer way to ask own or not

Asking whether an object has a property of its own has a newer, safer form. MDN recommends Object.hasOwn() over Object.prototype.hasOwnProperty(), because it works for null-prototype objects and with objects that have overridden the inherited hasOwnProperty() method. The standard lists it as Object.hasOwn ( obj, key ). The older way still works on everyday objects.

Why it fits here: It adds a careful tool to this topic's in operator: in also finds inherited keys, while Object.hasOwn looks only at the object's own.

Sources: MDN: Object.hasOwn(); ECMAScript Language Specification: Object.hasOwn

delete is not a dustbin

The word delete suggests clearing memory, but it does not. MDN notes that, unlike what common belief suggests, perhaps from languages like C++, the delete operator has nothing to do with directly freeing memory. It only removes a property from an object. Memory is managed indirectly, by breaking references: a value that nothing points to any more can be cleared away.

Why it fits here: It sharpens this topic's delete: it removes a label from an object, and the value goes only when nothing else holds it.

Sources: MDN: delete; ECMAScript Language Specification: OrdinaryDelete

In one line

Assigning to a property adds it or changes it, and delete removes it. A const object can still change inside, but the name cannot hold a different object, and { name, roll } is shorthand for { name: name, roll: roll }.

Two names, one object, and copies

At a glance

Two teachers sharing one register see the same marks: one writes, the other reads the change, because there was only ever one register. Objects behave the same way in code.

A name holds a reference, so assigning an object, or passing it to a function, shares the one object. Object.assign makes a shallow copy, which still shares the objects inside it. The function structuredClone makes a deep copy, which shares nothing. So the question to ask is always: is this the same object, or a copy?

Take a guess: If b = a for two objects and you change b.name, does a.name change?

Everything the arrays lesson said about sharing holds for objects, because an array is a kind of object. A name holds a reference to an object, so assigning it, or passing it to a function, shares the one object.

const a = { count: 1 };
const b = a;
b.count = 2;
console.log(a.count, a === b, { x: 1 } === { x: 1 });
2 true false

There is one object, with two names, so the change through b shows through a. And two objects made separately are never === to each other, whatever their properties: === asks whether two names lead to the same object.

A function that receives an object receives the reference, so a change it makes to a property is a change to the caller's object:

function birthday(person) {
  person.age = person.age + 1;
}
const asha = { name: "Asha", age: 14 };
birthday(asha);
console.log(asha.age);
15

This is often exactly the job, and sometimes a nasty surprise. If a function should not change the object it is given, it should make a copy and change that, or return a new object.

A shallow copy

Object.assign({}, original) copies every property of original into a new, empty object, and gives back the new object:

const o = { a: 1 };
const copy = Object.assign({}, o);
copy.a = 2;
console.log(o.a, copy.a);
1 2

But it copies only one level. If a property holds another object, the copy gets a reference to that same inner object, not a copy of it:

const o = { a: 1, inner: { b: 2 } };
const copy = Object.assign({}, o);
copy.inner.b = 99;
console.log(o.inner.b);
99
Shallow copy

A copy of an object's top level only. Its properties that hold objects or arrays still share them with the original.

A deep copy

structuredClone(original) copies all the way down, every inner object and array included, so nothing is shared:

const o = { a: 1, inner: { b: 2 } };
const deep = structuredClone(o);
deep.inner.b = 99;
console.log(o.inner.b, deep.inner.b);
2 99
Deep copy

A copy of an object and of every object and array inside it, so that the copy shares nothing with the original.

WayCopiesInner objects
const b = a;nothing: a second nameshared
Object.assign({}, a)the top levelshared
structuredClone(a)everythingcopied

The modern JavaScript step shows a shorter way to write a shallow copy, with three dots. A deep copy cannot copy functions, so it is for objects that hold only data, which is most of them.

Worked example 4

A school's timetable for Monday is an object with a list of periods. Friday has the same periods except that the last is sport. Make Friday's timetable without changing Monday's.

What we have: Monday's timetable, an object holding an array of periods

What we need: a Friday timetable whose last period is sport, and Monday unchanged

The plan: the periods are an array inside the object, so a shallow copy would share them; make a deep copy, then change it

const monday = { day: "Mon", periods: ["maths", "science", "art"] };
const friday = structuredClone(monday);
friday.day = "Fri";
friday.periods[2] = "sport";
console.log(monday.periods, friday.periods);
[ 'maths', 'science', 'art' ] [ 'maths', 'science', 'sport' ]

Friday ends with sport, and Monday still ends with art.

Check: monday.periods === friday.periods is false: they are two arrays.

A path that fails: using Object.assign({}, monday). The day is copied, but the periods array is shared, so the change to Friday's last period changes Monday's too.

When you are stuck: an object changed when you did not change it

Look for another name that holds the same object, or a function it was passed to.

If you made a copy with Object.assign, check for objects or arrays inside it: those are still shared.

Use structuredClone for a copy that shares nothing.

Remember that === between objects asks whether they are the same object.

Your turn

const x = { n: 1 };
const y = x;
const z = Object.assign({}, x);
y.n = 5;
console.log(x.n, z.n);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
5 1
  1. y is a second name for x's object, so x.n becomes 5.
  2. z is a copy made before the change: 1.

It prints 5 1.

Why does a change to copy.inner.b change the original after Object.assign({}, o)?Tap to reveal
  1. Object.assign copies the top level only.
  2. copy.inner holds a reference to the same inner object as o.inner.

Because the copy is shallow: the inner object is shared.

Write a function older(person) that returns a new object with the age one more, without changing the person given.Tap to reveal
function older(person) {
  const copy = Object.assign({}, person);
  copy.age = copy.age + 1;
  return copy;
}
const asha = { name: "Asha", age: 14 };
console.log(older(asha).age, asha.age);
15 14

The copy is 15, and asha stays 14.

Did you know?

Two equal-looking objects are not equal

Two objects with the same contents are still two objects. MDN states the rule for ===: if both operands are objects, it returns true only if they refer to the same object. So { a: 1 } === { a: 1 } is false, while a === b is true after b = a. Comparing two objects by their contents needs code that checks each property.

Why it fits here: It is this topic's sharing rule seen from the other side: === asks whether two names hold one object, not whether two objects look alike.

Sources: MDN: Strict equality (===); ECMAScript Language Specification: SameValueNonNumber

What a deep copy cannot copy

Even structuredClone has limits. MDN explains that function objects cannot be duplicated by the structured clone algorithm; trying throws a DataCloneError, and so does cloning DOM nodes. The HTML standard's steps say the same: if the value is callable, throw a DataCloneError. An object with methods loses nothing to sharing, but it cannot be deep-copied whole.

Why it fits here: It adds a warning to this topic's deep copies: they suit plain data, such as a student's marks, not objects that carry methods.

Sources: MDN: The structured clone algorithm; WHATWG: HTML Standard, Structured data

In one line

A name holds a reference, so assigning an object or passing it to a function shares it. Object.assign makes a shallow copy, which still shares inner objects; structuredClone makes a deep copy that shares nothing.

Methods and this

At a glance

A calculator does not only hold numbers; it also knows how to add them. An object can hold actions too. A function kept in an object is a method, and inside it, this means the object before the dot in the call.

Write methods in the short form, as name() { ... }, not as arrows, and use arrows for callbacks inside them. To make many objects of the same shape, write a factory function that builds and returns one each time it is called.

Take a guess: Inside shop.total(), what does this mean?

A shopping cart is not only a list of items. It can also count them, add up their prices, and empty itself. Those jobs belong with the cart, so an object can carry them, as functions kept in its properties.

Method

A function kept in a property of an object, and called with a dot: cart.count(). You have used methods since the values lesson, such as the string method toUpperCase.

const cart = {
  items: ["rice", "dal"],
  count() {
    return this.items.length;
  },
};
console.log(cart.count());
2

The method is written count() { ... }, a short form of count: function () { ... }. Inside it, the word this means the object that the method was called on: here, cart. So this.items is cart's items.

this

Inside a method, the object that the method was called on: in cart.count(), this is cart. It is decided by how the method is called, not by where it is written.

this depends on the call

Because this is decided by the call, the same method can lose its object. Called with a dot, it has one. Copied into a loose name and called alone, it has none. And an arrow function written as a method never gets the object at all, because, as the functions lesson warned, arrows do not get a this of their own:

const shop = {
  name: "Ravi Stores",
  isShop() {
    return this === shop;
  },
  arrowIsShop: () => this === shop,
};
console.log(shop.isShop(), shop.arrowIsShop());
const loose = shop.isShop;
console.log(loose());
true false
false

The first call has the dot, so this is shop. The arrow, though written inside the braces of shop, takes this from the code around the object, so it is not shop. The loose call has no dot in front, so this is not shop either. The habit that avoids all of it: write methods in the short form name() { ... }, and call them with their object and a dot.

Arrows are the right choice one level further in, inside a method. There, an arrow takes this from the method around it, which is exactly the object:

const shop = {
  name: "Ravi Stores",
  items: ["tea", "vada"],
  list() {
    return this.items.map((item) => `${item} at ${this.name}`);
  },
};
console.log(shop.list());
[ 'tea at Ravi Stores', 'vada at Ravi Stores' ]

Many objects of one shape: factory functions

A school has hundreds of students, each an object of the same shape. A function that makes and returns such an object is called a factory function. Each call makes a fresh object, with its own properties and the same methods:

function makeStudent(name, roll) {
  return {
    name,
    roll,
    label() {
      return `${this.roll}: ${this.name}`;
    },
  };
}
const s1 = makeStudent("Asha", 42);
const s2 = makeStudent("Ravi", 7);
console.log(s1.label(), s2.label());
42: Asha 7: Ravi

The modern JavaScript step shows classes, a second way to make many objects of one shape. Factory functions are simpler, and many programs use nothing else.

Getters and setters

Sometimes a property should be worked out each time it is read, or checked each time it is set. A getter, written with get, is a method that runs when a property is read, and looks like a plain property from outside. A setter, written with set, runs when the property is assigned:

const account = {
  paise: 33000,
  get rupees() {
    return this.paise / 100;
  },
  set rupees(value) {
    this.paise = Math.round(value * 100);
  },
};
console.log(account.rupees);
account.rupees = 450.75;
console.log(account.paise, account.rupees);
330
45075 450.75

The account keeps money in paise, the safe way of the values lesson, but anyone reading it can use rupees. Reading account.rupees runs the getter, with no brackets. Assigning to it runs the setter, which rounds to whole paise before storing.

A method can also give back this, so that calls can be chained:

const counter = {
  count: 0,
  add() {
    this.count++;
    return this;
  },
};
counter.add().add();
console.log(counter.count);
2

Worked example 5

A canteen's bill is an object with a list of items, each a name and a price. Give it a method total that adds up the prices, and a method line that gives the text Bill: ₹total. The items are tea at ₹15 and dosa at ₹60.

What we have: an object with an array of items

What we need: two methods that use the object's own items

The plan: write both methods in the short form, use this.items, and let line call this.total()

const bill = {
  items: [{ name: "tea", price: 15 }, { name: "dosa", price: 60 }],
  total() {
    return this.items.reduce((s, i) => s + i.price, 0);
  },
  line() {
    return `Bill: ₹${this.total()}`;
  },
};
console.log(bill.total(), bill.line());
75 Bill: ₹75
  1. line calls another method of the same object through this, so it works for any bill made this way.

The total is 75, and the line reads Bill: ₹75.

Check: 15 + 60 = 75.

A path that fails: writing total as an arrow: total: () => this.items.reduce(...). The arrow does not get the bill as this, so this.items is not the bill's items, and the call fails.

When you are stuck: this is not the object you expected

Look at the call, not the definition: this is the object before the dot.

A method copied into a loose name, or passed as a callback, loses its object.

Write methods in the short form name() { ... }, not as arrows.

Inside a method, use arrows for callbacks: they keep the method's this.

Your turn

const lamp = {
  street: "Harbour Road",
  oil: 3,
  refill() {
    this.oil = 10;
    return `${this.street}: ${this.oil}`;
  },
};
console.log(lamp.refill(), lamp.oil);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Harbour Road: 10 10
  1. refill is called on lamp, so this is lamp.
  2. It sets lamp's oil to 10 and returns the line.
  3. lamp.oil is now 10.

It prints Harbour Road: 10 10.

In shop.isShop(), what is this, and how is it decided?Tap to reveal
  1. this is decided by the call.
  2. The object before the dot is shop, so this is shop.

this is shop, the object before the dot.

Write a factory function makeLamp(street) that returns an object with street, oil set to 0, and a method fill() that sets oil to 10.Tap to reveal
function makeLamp(street) {
  return {
    street,
    oil: 0,
    fill() {
      this.oil = 10;
    },
  };
}
const lamp = makeLamp("Inkwell Lane");
lamp.fill();
console.log(lamp);
{ street: 'Inkwell Lane', oil: 10, fill: [Function: fill] }

Each call makes a fresh lamp with its own oil.

Did you know?

Objects without classes

Objects can exist without any class. Self is an object-oriented language based on the concept of prototypes, and it began as a dialect of Smalltalk. Its own site describes it as a prototype-based dynamic language built on simplicity, uniformity, concreteness and liveness. In such a language an object is made directly, the way a JavaScript factory function makes one, with no class first.

Why it fits here: It explains why this topic can make objects with a plain function: in a prototype-based language, objects need no class to come from.

Sources: Wikipedia: Self (programming language); The Self language

Classes built on prototypes

The class keyword came late. ECMAScript 2015 added Class Definitions, and MDN explains that classes in JS are built on prototypes, with some syntax and meaning of their own. So a class is mostly a tidier way to write objects that share methods through a prototype, which JavaScript could already do. Factory functions remain a plain, working way to build many objects.

Why it fits here: It places this topic's factory functions in history: they did the work of classes long before the class keyword existed.

Sources: ECMAScript 2015 Language Specification; MDN: Classes

In one line

A method is a function kept in an object, and this inside it is the object before the dot in the call. Write methods in the short form, not as arrows, use arrows for callbacks inside them, and make many objects of one shape with a factory function.

Looping over an object, and arrays of objects

At a glance

A class teacher reads down a list of students, and for each one reads the same boxes: name, marks, attendance. Most data in programs looks like that list: an array of objects.

The for...in loop gives each key of one object, and Object.keys, Object.values and Object.entries turn an object into arrays for the array methods. For an array of objects, map, filter, reduce and sort do the work, reading a property inside each callback. A shop's orders, a school's results and a city's buses all fit this shape.

Take a guess: Which method turns an object into an array of [key, value] pairs?

A report card lists each subject and its mark. To print it, or add up its marks, a program must go through every property of an object. Objects are not iterable like arrays, so for...of does not work on them directly, but there are three good ways.

for...in: every key

for...in, which the loops lesson warned against for arrays, was made for exactly this: it gives each key of an object in turn. Use the key with brackets to reach the value:

const marks = { maths: 88, science: 92, english: 79 };
for (const subject in marks) {
  console.log(subject, marks[subject]);
}
maths 88
science 92
english 79

Object.keys, Object.values and Object.entries

Three built-in functions turn an object into an array, which can then use every array method of the last two lessons:

const marks = { maths: 88, science: 92, english: 79 };
console.log(Object.keys(marks), Object.values(marks), Object.entries(marks));
[ 'maths', 'science', 'english' ] [ 88, 92, 79 ] [ [ 'maths', 88 ], [ 'science', 92 ], [ 'english', 79 ] ]

Object.keys gives the keys, Object.values the values, and Object.entries both, as an array of [key, value] pairs. A total of the marks is then one reduce away:

const marks = { maths: 88, science: 92 };
const total = Object.values(marks).reduce((s, m) => s + m, 0);
console.log(total);
180

Arrays of objects

Most real data is an array of objects: a list of products, of students, of orders, each an object of the same shape. The array methods of the loops lesson then work on the list, and the callbacks read each object's properties:

const items = [
  { name: "tea", price: 15 },
  { name: "vada", price: 25 },
  { name: "dosa", price: 60 },
];
console.log(items[1].name, items.map((i) => i.price), items.filter((i) => i.price > 20).length);
vada [ 15, 25, 60 ] 2

items[1].name reads from the left: items[1] is the second object, and .name is its name. map pulls one property out of every object, and filter keeps the objects that pass a test. Sorting works the same way, with a compare function that reads a property:

const items = [
  { name: "tea", price: 15 },
  { name: "vada", price: 25 },
];
const cheapest = items.toSorted((a, b) => a.price - b.price)[0];
console.log(cheapest.name);
tea

Worked example 6

A school's results are an array of objects, each with a name and marks. Asha has 412, Ravi 389 and Meera 455. Find the names of those with 400 or more, and the topper's name.

What we have: an array of three result objects

What we need: the names with 400 or more, and the name with the highest marks

The plan: filter then map for the names; toSorted, largest first, for the topper

const results = [
  { name: "Asha", marks: 412 },
  { name: "Ravi", marks: 389 },
  { name: "Meera", marks: 455 },
];
const good = results.filter((r) => r.marks >= 400).map((r) => r.name);
const topper = results.toSorted((a, b) => b.marks - a.marks)[0].name;
console.log(good, topper);
[ 'Asha', 'Meera' ] Meera

Asha and Meera have 400 or more, and the topper is Meera.

Check: 455 is the largest of 412, 389 and 455.

A path that fails: sorting results with results.sort(...) to find the topper. It works, but it changes the order of the list, which the rest of the page may rely on. toSorted leaves the list as it was.

When you are stuck: a loop over an object does not work

for...of does not work on a plain object: use for...in, or loop over Object.keys, values or entries.

Inside for...in, read the value with brackets: obj[key].

For an array of objects, read the property inside the callback: (i) => i.price.

Print one object of the array, to check the property names.

Your turn

const stock = { rice: 10, dal: 0, oil: 4 };
console.log(Object.keys(stock).length, Object.values(stock).filter((n) => n > 0).length);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
3 2
  1. There are three keys.
  2. Two values are above 0: 10 and 4.

It prints 3 2.

How do you print every key and value of { a: 1, b: 2 } with Object.entries?Tap to reveal
for (const [key, value] of Object.entries({ a: 1, b: 2 })) {
  console.log(key, value);
}
a 1
b 2
  1. Object.entries gives pairs, and the brackets in the loop name the two parts of each pair; the modern JavaScript step explains that shape.

Loop over Object.entries(obj).

From [{ name: "tea", price: 15 }, { name: "dosa", price: 60 }], get the array of names.Tap to reveal
console.log([{ name: "tea", price: 15 }, { name: "dosa", price: 60 }].map((i) => i.name));
[ 'tea', 'dosa' ]

map((i) => i.name) gives tea and dosa.

Did you know?

Grouping without a loop

Grouping a list, such as students by class or orders by city, once took a hand-written loop. Object.groupBy now does it: it groups the elements of an iterable according to the string values a callback returns, and gives back an object with one property per group. MDN shows it working across browsers since March 2024, and the standard lists it as Object.groupBy ( items, callback ).

Why it fits here: It saves this topic's most common loop over an array of objects: sorting items into groups by one property.

Sources: MDN: Object.groupBy(); ECMAScript Language Specification: Object.groupBy

Values and entries arrived later

Turning an object into arrays was not always complete. Object.keys was already in ECMAScript 5.1; Object.values and Object.entries followed in ECMAScript 2017, a proposal championed by Jordan Harband according to TC39's list of finished proposals. Before them, getting each value meant looping over the keys and reading every property by hand.

Why it fits here: It explains why older code reaches values through keys, where this topic uses Object.values and Object.entries directly.

Sources: TC39: Finished Proposals; MDN: Object.entries(); ECMAScript 5.1 Language Specification

In one line

for...in gives each key of an object; Object.keys, values and entries turn it into arrays for the array methods. Most data is an array of objects, worked on with map, filter, reduce and sort, reading a property in each callback.

Objects inside objects, and JSON

At a glance

A student's record may hold an address, and the address may hold a city and a pin code. Objects can sit inside objects, as boxes inside boxes, and each dot goes one level deeper.

When a level may be missing, ?. stops at the gap and gives undefined, and ?? supplies a default, so the program does not stop. JSON is objects written as text: JSON.stringify turns a value into it, and JSON.parse turns the text back into a value.

Take a guess: When a user has no address, can the program still read the city without stopping?

A user's profile holds an address, and the address holds a city and a PIN. Real data is built like that: objects inside objects, and arrays of objects inside objects. Each dot goes one level deeper.

const user = { name: "Ravi", address: { city: "Pune", pin: "411001" } };
console.log(user.address.city, user.phone?.number, user.address?.pin);
Pune undefined 411001

Read user.address.city from the left: user's address, then that address's city. The user has no phone, so user.phone is undefined. Reading a property of undefined is an error, which ?., the optional chaining of the conditionals lesson, turns into a quiet undefined:

const user = { name: "Ravi" };
console.log(user.phone.number);
Uncaught TypeError: Cannot read properties of undefined (reading 'number')
    at line 2

Use ?. where a part may be missing, and ?? to give a default for what is missing:

const user = { name: "Ravi", address: { city: "Pune" } };
console.log(user?.address?.city, user.address.pin ?? "no PIN yet");
Pune no PIN yet

An order is a good example of the mix: an object holding an array of objects. A total walks the array and reads two properties from each object inside it:

const order = { id: 7, items: [{ name: "tea", qty: 2, price: 15 }, { name: "vada", qty: 1, price: 25 }] };
const total = order.items.reduce((s, i) => s + i.qty * i.price, 0);
console.log(total, order.items.length);
55 2

JSON: objects as text

A program often has to send an object somewhere else: to a server, to a file, to another program. They cannot share the object itself, so they share text that describes it, in an agreed format.

JSON

JavaScript Object Notation: a text format for data that looks like JavaScript's objects and arrays, with every key in double quotes. JSON.stringify(value) turns a value into JSON text, and JSON.parse(text) turns JSON text back into a value.

const student = { name: "Asha", roll: 42 };
console.log(JSON.stringify(student), typeof JSON.stringify(student));
{"name":"Asha","roll":42} string
const text = '{"name":"Asha","roll":42}';
const back = JSON.parse(text);
console.log(back.name, back.roll + 1);
Asha 43

JSON is how almost every web service sends its data, as the APIs step of this path shows in full. It can hold strings, numbers, booleans, null, arrays and objects, and nothing else: no functions and no undefined. A JSON round trip, stringify then parse, is also an old way to make a deep copy of plain data:

const student = { name: "Asha", marks: { maths: 88 } };
const copy = JSON.parse(JSON.stringify(student));
copy.marks.maths = 10;
console.log(student.marks.maths, copy.marks.maths);
88 10

A common mistake

Putting an object straight into a template literal or joining it to a string. The object is turned into the text [object Object], which tells the reader nothing. Read the properties you want, or use JSON.stringify:

const o = { a: 1 };
console.log(`${o}`, `${JSON.stringify(o)}`);
[object Object] {"a":1}

Worked example 7

A delivery app receives an order from its server as JSON text. Turn it into an object, and print the customer's city and the number of items. The text is {"customer":{"name":"Meera","city":"Nagpur"},"items":["rice","oil"]}.

What we have: JSON text from a server

What we need: the city and the count of items

The plan: parse the text into an object, then read through the levels with dots

const text = '{"customer":{"name":"Meera","city":"Nagpur"},"items":["rice","oil"]}';
const order = JSON.parse(text);
console.log(order.customer.city, order.items.length);
Nagpur 2

The city is Nagpur, and there are 2 items.

Check: order.customer is an object, and order.items an array, exactly as the text described them.

A path that fails: reading text.customer without parsing. text is a string, and a string has no customer property, so it gives undefined.

When you are stuck: reading deep inside an object fails

Print each level on its own: console.log(user, user.address);, to see which level is missing.

Use ?. where a level may be missing, and ?? for a default.

If the data arrived as text, parse it with JSON.parse before reading it.

If you see [object Object], print the object with console.log, or turn it into text with JSON.stringify.

Your turn

const p = { name: "Asha", school: { city: "Pune" } };
console.log(p.school.city, p.school?.pin, p.club?.name);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Pune undefined undefined
  1. p.school.city is Pune.
  2. The school has no pin: undefined.
  3. There is no club, and ?. gives undefined instead of an error.

It prints Pune undefined undefined.

What does JSON.stringify({ ok: true, n: 3 }) give?Tap to reveal
console.log(JSON.stringify({ ok: true, n: 3 }));
{"ok":true,"n":3}

The text {"ok":true,"n":3}, with the keys in double quotes.

Why must JSON text be parsed before its properties are read?Tap to reveal
  1. JSON text is a string.
  2. A string does not have the properties described inside it; JSON.parse builds the object.

Because it is text until JSON.parse turns it into an object.

Did you know?

A format from a subset

JSON was not invented from nothing. Its home page says it is based on a subset of the JavaScript Programming Language Standard, ECMA-262 3rd Edition of December 1999. Its standard today, RFC 8259, calls it a lightweight, text-based, language-independent data interchange format, derived from the ECMAScript standard. So JSON looks like JavaScript, and nearly every language reads it.

Why it fits here: It explains why this topic's JSON looks so much like an object literal: it was taken from JavaScript's own way of writing objects.

Sources: JSON.org: Introducing JSON; RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format

What JSON leaves out

Not every value survives the trip into JSON. MDN explains that undefined, functions and symbols are not valid JSON values: JSON.stringify leaves them out of an object, or writes null in their place in an array. Infinity and NaN become null too, because the JSON standard does not permit them. So a value can come back from JSON.parse with less than it had.

Why it fits here: It is a trap of this topic's JSON: stringify a student with an undefined field, and that field is gone after parse.

Sources: MDN: JSON.stringify(); RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format

In one line

Each dot goes one level deeper into nested objects; ?. and ?? keep a missing level from stopping the program. JSON is objects as text: JSON.stringify turns a value into it, and JSON.parse turns it back.

Where it is used

Almost every piece of data a program handles is an object, or an array of them. Here is where each idea of this lesson shows up in real work.

What you learnedWhere it is usedA real example
objects and propertiesone record of anythinga student, a product, a payment, a train ticket
bracket notationkeys chosen while the program runsshowing the mark of the subject a teacher picks from a list
references and copieskeeping data safe from other codeediting a copy of a form's data, so that Cancel can restore the original
methods and thisan object that does its own jobsa cart that counts and totals its own items
factory functionsmany objects of one shapeone function that makes every student record of a school
getters and settersvalues worked out or checkeda balance kept in paise and shown in rupees
Object.keys, values and entriesgoing through an object's propertiesprinting every subject of a report card
arrays of objectslists of recordsa product list filtered by price and sorted by rating
nested objects and ?.data with parts that may be missinga profile whose address may not be filled in yet
JSONsending and saving dataan app asking a server for today's orders, and getting JSON text back

Mistakes and debugging

These are the slips that people meet most often with objects. Every output below is the real one, from the code shown.

1. A key spelt differently

const student = { name: "Asha" };
console.log(student.Name);
undefined

No error: keys are case-sensitive. The fix: print the object, and use the key exactly as it is written there.

2. A dot where brackets were needed

const marks = { science: 92 };
const chosen = "science";
console.log(marks.chosen);
undefined

No error: marks.chosen looks for a key named chosen. The fix: marks[chosen].

3. Reading below a level that is missing

const user = { name: "Ravi" };
console.log(user.phone.number);
Uncaught TypeError: Cannot read properties of undefined (reading 'number')
    at line 2

The fix: user.phone?.number, or give the user a phone first.

4. A second name taken for a copy

const a = { count: 1 };
const b = a;
b.count = 2;
console.log(a.count);
2

No error: both names share one object. The fix: structuredClone(a), or Object.assign({}, a) for one level.

5. A shallow copy with an object inside

const o = { inner: { b: 2 } };
const copy = Object.assign({}, o);
copy.inner.b = 99;
console.log(o.inner.b);
99

No error: the inner object is shared. The fix: structuredClone(o).

6. A method written as an arrow

const shop = {
  isShop: () => this === shop,
};
console.log(shop.isShop());
false

No error: an arrow does not get the object as this. The fix: isShop() { return this === shop; }.

7. An object put into text

const o = { a: 1 };
console.log(`Order: ${o}`);
Order: [object Object]

No error, and no information. The fix: read the properties you want, or use JSON.stringify(o).

8. A hyphen in an unquoted key

const item = { price-in-rupees: 15 };
Uncaught SyntaxError: Unexpected token '-'

The fix: quote the key, "price-in-rupees": 15, or use camelCase: priceInRupees.

The debugging corner: print the whole object

For any object that misbehaves, print it whole: console.log shows every key and value, nested ones included. Compare the keys you see with the keys your code uses. For an object that changed by itself, look for every name that holds it and every function it was passed to. In the Sources panel of the DevTools step, the Scope pane shows a paused object's properties, and the arrow beside it opens each nested level.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

The lesson in code

// make and read: a dot, or brackets for a key in a name
const student = { name: "Asha", roll: 42 };
const key = "roll";
console.log(student.name, student[key], student.city, "roll" in student);

// change: assign to add or change, delete to remove
student.city = "Pune";
delete student.roll;
console.log(student);

// share or copy: b = a shares; structuredClone copies all the way down
const copy = structuredClone(student);
copy.city = "Nagpur";
console.log(student.city, copy.city);

// methods: this is the object before the dot
const cart = {
  items: [15, 60],
  total() {
    return this.items.reduce((s, p) => s + p, 0);
  },
};
console.log(cart.total());

// loop: Object.keys, values and entries; arrays of objects with map
const marks = { maths: 88, science: 92 };
console.log(Object.keys(marks), Object.values(marks).reduce((s, m) => s + m, 0));

// nested and JSON: ?. for a missing level; stringify and parse
console.log(student.address?.pin, JSON.stringify({ ok: true }), JSON.parse("[1,2]").length);
Asha 42 undefined true
{ name: 'Asha', city: 'Pune' }
Pune Nagpur
75
[ 'maths', 'science' ] 180
undefined {"ok":true} 2
When you seeIt meansLook at
undefined from a propertythe key is spelt differently, or the key is in a namethe printed object; brackets
Cannot read properties of undefineda level above the property is missing?., and the level above
an object that changed by itselfanother name, or a function, shares itstructuredClone
a copy whose inner parts change the originala shallow copystructuredClone
this is not the objectan arrow as a method, or a loose callthe short method form, and the dot
[object Object] in textan object turned into textits properties, or JSON.stringify
SyntaxError: Unexpected token '-' in an objecta key with a hyphen and no quotesquotes, or camelCase

The story: One record for each lamp

You give each lamp one record with four labelled parts: its number, its street, its oil and when it was last lit. The forty records go into one list. When a lamp is taken down, its whole record goes with it, and nothing else moves.

That night the clockwork reads each record's own street and oil, and every lamp gets what it needs.

Master Verge reads one record aloud, label by label. "Now the notes travel together," he says. "Next, the clocks must reach out and change the city's panels themselves."

Reagents gathered: object, property, method, this, for...in, JSON.

Sources