CodeMIRAI
0 XP

Objects

2 min read 7 runnable examples Quiz included

An object groups related values under named properties (also called keys).

JavaScript
const user = {
  name: "Asha",
  age: 21,
  isMember: true,
};

console.log(user.name);        // dot notation
console.log(user["age"]);      // bracket notation

Adding, changing and deleting

JavaScript
const book = { title: "Clean Code", year: 2008 };
book.author = "Robert C. Martin";   // add
book.year = 2009;                   // change
delete book.year;                   // remove
console.log(book);

Bracket notation for dynamic keys

Use brackets when the key is in a variable or isn't a valid name:

JavaScript
const prices = { tea: 20, "iced coffee": 45 };
const item = "tea";
console.log(prices[item]);
console.log(prices["iced coffee"]);
console.log(prices.juice);          // missing key: undefined, no error

Methods

A function stored in an object is a method. Inside it, this refers to the object:

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

Looping over an object

JavaScript
const scores = { Asha: 92, Leo: 78, Mei: 85 };

for (const name in scores) {
  console.log(name, scores[name]);
}

console.log(Object.keys(scores));
console.log(Object.values(scores));
for (const [name, score] of Object.entries(scores)) {
  console.log(`${name}: ${score}`);
}

Nested objects and arrays

JavaScript
const order = {
  id: 1042,
  customer: { name: "Mei", city: "Osaka" },
  items: [
    { product: "Keyboard", price: 89.99 },
    { product: "Mouse", price: 24.5 },
  ],
};
console.log(order.customer.city);
console.log(order.items[1].product);
const total = order.items.reduce((sum, i) => sum + i.price, 0);
console.log(total.toFixed(2));

Shorthand and optional chaining

JavaScript
const name = "Leo";
const age = 30;
const person = { name, age };       // same as { name: name, age: age }
console.log(person);

console.log(person.address?.city);  // undefined instead of an error
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.