SyntaxPilot
Courses/JavaScript/Lesson 8

JavaScript · Lesson 8 of 40 · 12 min

Objects

queued

These are the notes for JavaScript episode 8. You will learn why parallel arrays fall out of step, how to create an object, keys, values and properties, dot vs bracket notation, what a missing key gives you, adding, updating and deleting properties, nested objects, the famous Cannot read properties of undefined error and its fix (?. and ??), the in operator, Object.keys, Object.values and Object.entries, arrays of objects, shorthand properties, methods and this, copying vs sharing an object, and Object.freeze. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js).

Why objects: Ravi's loyalty register

Ravi starts a loyalty card: for every regular customer, a name, a phone number and a visit count (ten visits = a free chai). With what we knew, the obvious way is three arrays, lined up by index: index 0 is Asha in all three lists.

Then one customer (also called Ravi) moves away, and we remove his name with splice, from the names list only:

const names = ["Asha", "Ravi", "Meena"];
const phones = ["98100", "98200", "98300"];
const visits = [12, 3, 7];
names.splice(1, 1);
console.log(`${names[1]}: ${phones[1]}, ${visits[1]} visits`);
Meena: 98200, 3 visits

No error, and a wrong answer: that's the phone and the visits of the customer who left. Meena's free chai message would go to the wrong person. Nothing ties a name to its phone except the hope that three separate lists ("parallel arrays") stay in step. We need all the facts about one customer packed together, each with a label. That is an object.

Objects: a contact card on your phone

A phone contact In JavaScript Meaning
One contact card const meena = { ... } an object, in curly brackets
Labels: Name, Mobile name: "Meena" a key, a colon, a value: one property
Tap "Mobile" to see it meena.phone read a property by its key
const meena = {
  name: "Meena",
  phone: "98300",
  visits: 7,
};
console.log(meena);
console.log(meena.name);
console.log(meena["phone"]);
console.log(meena.Visits);
{ name: 'Meena', phone: '98300', visits: 7 }
Meena
98300
undefined
  • An object is a set of properties inside { }, separated by commas. Each property is key: value.
  • Read a property with a dot (meena.name) or with square brackets and the key as a string (meena["phone"]).
  • Keys are case sensitive. A key that doesn't exist gives undefined, with no error, just like an array index past the end.
  • The comma after the last property (visits: 7,) is allowed and common: it makes adding a line later easier.

Values can be anything: numbers, strings, booleans, arrays, other objects, even functions.

Add, update, delete

const customer = { name: "Asha", visits: 12 };
customer.visits++;
customer.city = "Pune";
delete customer.name;
console.log(customer);
const field = "city";
console.log(customer[field]);
console.log(customer.field);
{ visits: 13, city: 'Pune' }
Pune
undefined
You want to... Write
update a value customer.visits++ or customer.visits = 13
add a new property just assign it: customer.city = "Pune"
remove a property delete customer.name
read a key stored in a variable customer[field] (brackets only)

customer.field looks for a key literally named "field", which doesn't exist. When the key is inside a variable, use square brackets. Like arrays (episode 7), a const object can change inside: const locks the name, not the contents.

Object basics

const c = { name: "Asha", visits: 12 };
            └─key─┘ └value┘
            └──── property ────┘
  • Read: c.name or c["name"]; key in a variable: c[field].
  • Add or update: c.city = "Pune"; remove: delete c.name.
  • Wrong key (c.Name) → undefined.

Nested objects: a delivery slip

A delivery slip In JavaScript
Order 101 (the slip) order
A box for the customer order.customer (an object inside)
An address box inside that order.customer.address.city (follow the dots)
const order = {
  id: 101,
  customer: { name: "Asha", address: { city: "Pune" } },
};
console.log(order.customer.address.city);
const walkIn = { id: 102 };
console.log(walkIn.customer.address.city);
Pune
TypeError: Cannot read properties of undefined (reading 'address')

This is probably the most common error in all of JavaScript. A walk-in order has no customer, so walkIn.customer is undefined. A missing key on its own is fine (it's just undefined), but asking undefined for a key crashes: it's like asking for the city of a customer box that isn't on the slip. The message even tells you which key it was trying to read ('address'), so the thing before it is the one that's missing.

Optional chaining ?. and the fallback ??

const walkIn = { id: 102 };
console.log(walkIn.customer?.address?.city);
console.log(walkIn.customer?.name ?? "Walk-in customer");
console.log("id" in walkIn, "customer" in walkIn);
undefined
Walk-in customer
true false
Operator Name Meaning
a?.b optional chaining if a is undefined (or null), stop and give undefined instead of crashing
x ?? y nullish coalescing use y only when x is undefined or null
"key" in obj the in operator does this key exist? true / false

?? vs || (episode 3): || replaces any falsy value, including 0 and ""; ?? only replaces undefined and null:

const settings = { theme: "dark", size: 0 };
console.log(settings.size || 16, settings.size ?? 16);
16 0

Use ?. when something may legitimately be missing. Don't sprinkle it everywhere: if a value must exist, a crash tells you about the bug early.

Object.keys, values and entries

const menu = { chai: 10, samosa: 12, vadaPav: 15 };
console.log(Object.keys(menu));
console.log(Object.values(menu));
console.log(Object.entries(menu));
console.log(`${Object.keys(menu).length} items`);
[ 'chai', 'samosa', 'vadaPav' ]
[ 10, 12, 15 ]
[ [ 'chai', 10 ], [ 'samosa', 12 ], [ 'vadaPav', 15 ] ]
3 items
  • Object.keys(o): an array of the keys. Object.values(o): an array of the values. Object.entries(o): an array of [key, value] pairs.
  • Objects have no length: count properties with Object.keys(o).length.
  • You can also loop over the keys with for...in (episode 6):
for (const item in menu) {
  console.log(`${item}: Rs ${menu[item]}`);
}
chai: Rs 10
samosa: Rs 12
vadaPav: Rs 15

Arrays of objects: the menu

const menu = [
  { item: "chai", price: 10, veg: true },
  { item: "samosa", price: 12, veg: true },
  { item: "egg roll", price: 40, veg: false },
];
for (const dish of menu) {
  const tag = dish.veg ? "veg" : "non-veg";
  console.log(`${dish.item} (${tag}): Rs ${dish.price}`);
}
console.log(menu[2].item, menu.length);
chai (veg): Rs 10
samosa (veg): Rs 12
egg roll (non-veg): Rs 40
egg roll 3

menu[2].item: the index picks the thing, the dot picks the fact. A list of objects is the shape of almost all real data: products in a shop, messages in a chat, rows from a database, the JSON an API sends you (episode 19).

Shorthand properties, methods and this

const name = "Ravi";
const visits = 3;
const customer = { name, visits };
console.log(customer);
const stall = {
  owner: "Ravi",
  greet() {
    return `Welcome to ${this.owner}'s stall!`;
  },
};
console.log(stall.greet());
{ name: 'Ravi', visits: 3 }
Welcome to Ravi's stall!
  • Shorthand property: when the key and the variable have the same name, { name } means { name: name }.
  • A function stored in an object is a method. greet() { ... } is the short way to write one; call it with stall.greet().
  • Inside a method, this means the object the method was called on, so this.owner is "Ravi".
  • You've used methods since episode 1: console is an object and log is its method. Functions get episode 9, and this gets a full episode (17).

Copying vs sharing: the discount that changed the menu

const original = { item: "chai", price: 10 };
const shared = original;
shared.price = 0;
console.log(original);
const copy = { ...original, price: 15 };
console.log(original, copy);
console.log({ a: 1 } === { a: 1 });
{ item: 'chai', price: 0 }
{ item: 'chai', price: 0 } { item: 'chai', price: 15 }
false
  • shared = original does not copy: it's a second label on the same object (a reference). The real menu now says chai costs ₹0.
  • { ...original } (the spread syntax, episode 12) makes a new object with the same properties; keys written after it (price: 15) override.
  • === on objects asks "is it the same object?", not "do they look the same?", so two look-alike objects are false.

Shallow copy warning: spread copies only the top level. Objects nested inside are still shared:

const deep = { a: { b: 1 } };
const shallow = { ...deep };
shallow.a.b = 99;
console.log(deep.a.b);
const real = structuredClone({ a: { b: 1 } });
console.log(real);
99
{ a: { b: 1 } }

For a full (deep) copy of plain data, use structuredClone(obj).

Object.freeze: a read-only object

const price = Object.freeze({ chai: 10 });
price.chai = 100;
console.log(price.chai);
10

The change is silently ignored (in strict mode, which modules and classes use, it throws a TypeError instead). Use Object.freeze for settings that must never change, like a price list. Like spread, it's shallow: nested objects are not frozen.

Common mistakes (and what really happens)

You wrote What happens Why Fix
meena.Visits (no error) undefined keys are case sensitive meena.visits
customer.field (key in a variable) (no error) undefined the dot looks for a key named field customer[field]
walkIn.customer.address TypeError: Cannot read properties of undefined (reading 'address') customer is undefined walkIn.customer?.address
const shared = original; (no error) both change same object, two names { ...original } or structuredClone
{ a: 1 } === { a: 1 } (no error) false === asks "same object?" compare the properties
menu.length on an object (no error) undefined objects have no length Object.keys(menu).length
three parallel arrays (no error) wrong data lists fall out of step an array of objects

Mini project: a cart and a bill

const cart = [
  { item: "chai", price: 10, qty: 3 },
  { item: "samosa", price: 12, qty: 2 },
  { item: "vada pav", price: 15, qty: 1 },
];
let total = 0;
for (const line of cart) {
  const cost = line.price * line.qty;
  total += cost;
  console.log(`${line.item.padEnd(9)} x${line.qty}  Rs ${cost}`);
}
const bill = { items: cart.length, total, paid: false };
bill.paid = true;
console.log(bill);
chai      x3  Rs 30
samosa    x2  Rs 24
vada pav  x1  Rs 15
{ items: 3, total: 69, paid: true }
  • The cart is an array of objects: one object per line of the bill.
  • for...of hands you each line; line.price * line.qty is its cost.
  • padEnd(9) (episode 4) pads the item name to 9 characters so the columns line up.
  • The bill object uses the shorthand total and is updated after it's created.

Try adding your own items, or a discount property to the bill.

Practice

  1. Make an object for your favourite movie with title, year and myRating.
  2. Add a director key, then delete myRating.
  3. Print each key and value of { chai: 10, samosa: 12 }.
  4. From an array of 3 students (name, marks), print who scored the most.
Solutions and hints

1 and 2.

const movie = { title: "Lagaan", year: 2001, myRating: 9 };
console.log(movie);
movie.director = "Ashutosh Gowariker";
delete movie.myRating;
console.log(movie);
{ title: 'Lagaan', year: 2001, myRating: 9 }
{ title: 'Lagaan', year: 2001, director: 'Ashutosh Gowariker' }
  1. for...in gives each key; brackets look up its value:
const menu = { chai: 10, samosa: 12 };
for (const key in menu) {
  console.log(`${key}: ${menu[key]}`);
}
chai: 10
samosa: 12
  1. Keep the best student so far, and replace it when you find a higher mark:
const students = [
  { name: "Asha", marks: 82 },
  { name: "Ravi", marks: 91 },
  { name: "Meena", marks: 77 },
];
let best = students[0];
for (const s of students) {
  if (s.marks > best.marks) {
    best = s;
  }
}
console.log(`${best.name} scored the most: ${best.marks}`);
Ravi scored the most: 91

Quick quiz

What does this print?

const a = { score: 5 };
const b = a;
b.score = 9;
console.log(a.score);
  • A. 5
  • B. 9
  • C. undefined
  • D. TypeError
Answer

B. b = a does not copy the object: a and b are two names for the same object, so changing b.score changes a.score too.

Interview questions

  • What is an object in JavaScript? What are keys, values and properties?
  • When must you use bracket notation instead of dot notation?
  • What do you get when you read a key that doesn't exist? When do you get a TypeError instead?
  • What does ?. do? What's the difference between ?? and ||?
  • How do you count the properties of an object? How do you loop over them?
  • What's the difference between Object.keys, Object.values and Object.entries?
  • What does const b = a do for objects? How do you make a shallow copy and a deep copy?
  • Why is { a: 1 } === { a: 1 } false?
  • What does Object.freeze do? Is it deep or shallow?
  • What is a method? What does this refer to inside a method?

Glossary

Term Meaning Example
Object labelled values describing one thing, in curly brackets { name: "Meena", visits: 7 }
Key the label of a value in an object name
Value the data stored under a key "Meena"
Property one key together with its value visits: 7
Dot notation reading a property with a dot meena.name
Bracket notation reading a property with a string key meena["phone"], c[field]
Parallel arrays separate lists lined up by index names, phones, visits
delete removes a property delete c.name
Nested object an object stored as a value inside another order.customer.address
undefined "no value": a missing key meena.Visits
TypeError an error for using a value the wrong way reading a key of undefined
Optional chaining ?. stops and gives undefined instead of crashing walkIn.customer?.name
Nullish coalescing ?? a fallback only for undefined / null x ?? "default"
in operator checks if a key exists "id" in walkIn → true
Object.keys array of an object's keys ["chai", "samosa"]
Object.values array of an object's values [10, 12]
Object.entries array of [key, value] pairs [["chai", 10]]
Array of objects a list where each item is an object menu[2].item
Shorthand property { name } means { name: name } { total }
Method a function stored in an object stall.greet()
this inside a method: the object it was called on this.owner
Reference a label pointing at an object; = copies the label shared = original
Spread ... copies an object's properties into a new one { ...original }
Shallow copy copies only the top level spread, Object.assign
Deep copy copies nested objects too structuredClone(obj)
Object.freeze makes an object read-only (shallow) Object.freeze({ chai: 10 })

Summary

  • An object packs labelled facts about one thing: { key: value }. Each key: value is a property.
  • Read with o.key or o["key"]; a key in a variable needs o[k]. Assign to add or update, delete to remove.
  • A missing key is undefined; reading a key of undefined is a TypeError. Use ?. to stop safely and ?? for a fallback.
  • Object.keys / values / entries turn an object into arrays; count properties with Object.keys(o).length.
  • An array of objects is the shape of most real data: the index picks the thing, the dot picks the fact.
  • A function in an object is a method; this is the object.
  • = shares an object; { ...o } copies (shallow), structuredClone copies deep; === asks "same object?". Object.freeze makes it read-only.

Next episode: functions. Ravi's bill formula is copy-pasted in three places; GST changes, one copy is missed, and a bill comes out wrong. So you'll invent functions, arrow functions and default parameters.