Skip to content
Lesson 6 of 10 · JavaScript for Beginners

Objects

Group related values with objects, read and change properties, loop over keys, and convert to JSON.

18 min

An object groups related values under names (properties). It is the way JavaScript describes a thing:

javascript12 lines
const book = {
  title: "Night Trains",
  price: 9.99,
  tags: ["fiction", "travel"],
};

console.log(book.title);        // dot notation
console.log(book["price"]);     // bracket notation: any string, even in a variable
book.stock = 12;                // add a property
book.price = 8.99;              // change one
delete book.tags;               // remove one
console.log("stock" in book);   // true

Use dot notation when you know the name, and brackets when the name is in a variable: book[key].

A property can hold a function, called a method:

javascript5 lines
const counter = {
  count: 0,
  add() { this.count += 1; },
};
counter.add();   // this is the object before the dot

javascript6 lines
Object.keys(book);      // ["title", "price", "stock"]
Object.values(book);    // the values
Object.entries(book);   // [["title", "Night Trains"], ...]
for (const [key, value] of Object.entries(book)) {
  console.log(key, value);
}

javascript2 lines
const { title, price } = book;          // pull properties into variables
const sale = { ...book, price: 7.99 };  // a copy with one change

Real data is usually an array of objects: [{ name: "Ada", age: 36 }, ...]. To send data over a network or save it, convert to text with JSON.stringify(obj) and back with JSON.parse(text).

Like arrays, objects are stored by reference: const b = a points at the same object. Copy with { ...a }.

Choosing between an array and an object.

Array

Look things up by
position (0, 1, 2...)
Good for
a list of similar things: scores, names
Order
meaningful

Best for the steps, the rows

Object

Look things up by
name (a key)
Good for
one thing with several facts, or a lookup table
Order
not what you rely on

Best for a book, a user, counts by word

Exercise3 checks
javascript

Write tally(items) that returns an object counting how many times each item appears.

tally(["a", "b", "a"]) is { a: 2, b: 1 }.

Your code must satisfy

  • tally(["a", "b", "a"])→{"a":2,"b":1}simple
  • tally([])→[]empty
  • tally(["to", "be", "or", "not", "to", "be"])→{"to":2,"be":2,"or":1,"not":1}words
starter code5 lines
function tally(items) {
  const counts = {};
  
  return counts;
}
Exercise4 checks
javascript

Write cartTotal(cart). cart is an array of objects like { name: "pen", price: 1.5, qty: 4 }. Return the total price (price times qty, added up), rounded to 2 decimals. An empty cart is 0.

Your code must satisfy

  • cartTotal([{name: "pen", price: 1.5, qty: 4}, {name: "book", price: 12, qty: 1}])→18two items
  • cartTotal([])→0empty
  • cartTotal([{name: "x", price: 0.1, qty: 3}])→0.3rounding
  • cartTotal([{name: "tea", price: 2.35, qty: 2}])→4.7one
starter code3 lines
function cartTotal(cart) {
  
}
Exercise1 case
javascript

Given the object below, print each of its entries as key: value, one per line, using Object.entries.

code2 lines
name: Ada
age: 36

Your code must satisfy

  • entries
starter code1 line
const person = { name: "Ada", age: 36 };
Common misconception

“`const copy = original` makes an independent copy of an object.”

It works that way for numbers and strings.

What is actually true

Objects are stored by reference. copy and original are two names for the same object, so changing one changes the other. Copy with { ...original } (one level deep) instead.

How to catch yourself

A surprising change in data you did not touch usually means two names share one object.

  • An object holds named properties: obj.name, or obj[key] when the name is in a variable.
  • Object.keys, values and entries let you loop over an object.
  • Arrays of objects are the usual shape of real data.
  • Objects are shared by reference: copy with { ...obj }.
Check yourself

Object checks.

1Multiple choice

const o = { a: 1 }; o.b = 2; What is Object.keys(o).length?

  • A1
  • B2
  • C0
  • Derror
2Multiple choice

Which reads a property whose name is in the variable key?

  • A`o.key`
  • B`o[key]`
  • C`o(key)`
  • D`o->key`
3Multiple choice

What does { ...a, x: 9 } do?

  • AChanges `a`
  • BMakes a copy of `a` with `x` set to 9
  • CDeletes `x`
  • DErrors
4Multiple choice

const a = { n: 1 }; const b = a; b.n = 5; What is a.n?

  • A1
  • B5
  • Cundefined
  • Derror
5Fill the blanks

To turn an object into text for saving, use JSON.(obj).

Capitalisation, spacing and punctuation are ignored when grading.

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of JavaScript for Beginners is planned around your week. Free.