Objects

Programming Languages · JavaScript Objects · 14 min

Group related values under named keys, give them methods, and loop over them.

Making an object

An object groups related values under names called keys. Write it in curly braces as key: value pairs, separated by commas. Read a value with a dot.

const dog = { name: "Rex", age: 3 };
console.log(dog.name); // Rex
  • Create a const object book with title set to "Dune" and pages set to 412.

  • Print book.title.

Dots and brackets

There are two ways to read a key. Dot: car.brand. Brackets with a string: car["brand"].

Brackets shine when the key is stored in a variable:

const pick = "brand";
console.log(car[pick]); // same as car.brand

car.pick would look for a key literally called pick.

  • Print car.brand using a dot.

  • Print the value for the key stored in key, using brackets.

Adding and updating keys

Set a key with =. If the key exists, its value is updated. If it doesn't, it's added.

const cat = { name: "Tom" };
cat.name = "Tim"; // update
cat.age = 4;       // add
  • Update player.level to 2.

  • Add a new key coins set to 50.

  • Print Mia is level 2 with 50 coins using a template literal and the player's keys.

Methods: functions inside objects

A function stored in an object is called a method. Inside it, this means "the object I belong to", so this.name reads the object's own name.

const cat = {
  name: "Tom",
  meow() {
    console.log(`${this.name} says meow`);
  },
};
cat.meow(); // Tom says meow
  • Add a method greet() to robot that prints Beep! I am and its name, using this.name.

  • Below the object, call robot.greet().

Looping over an object

for...in walks through an object's keys. Use brackets to get each value:

for (const key in pet) {
  console.log(key, pet[key]);
}

Object.entries(obj) gives you [key, value] pairs instead, which you can unpack straight away:

for (const [key, value] of Object.entries(pet)) { ... }
  • Use for...in to print each item as apples: 5, pears: 2 and so on.

  • Then use Object.entries to print each one the other way round: 5 apples, 2 pears, 9 plums.

Put it together: a contact card

Update a contact, then print every detail with a loop. New keys go at the end, so the loop prints them last.

  • Add a key age set to 30.

  • Change city to "Milan".

  • Loop over contact and print each pair as key = value.

More in JavaScript Objects

Previous: Array Methods · Next: Classes