Skip to content
BetaDE
Lesson 6 of 11JavaScript

JavaScript · Lesson 6 · 30 minutes

Objects

What you'll learn

  • Create objects with properties
  • Read and change properties
  • Work with arrays of objects

Creating an object

An object groups values that belong together under names – like a profile:

const dog = {
  name: "Rex",
  age: 4,
  tricks: ["sit", "down"],
};

console.log(dog.name);
console.log(dog.tricks.length);
console.log(dog);

Python comparison: this is similar to a dictionary. Instead of dog["name"], in JavaScript you usually write dog.name.

Changing and adding

const player = { name: "Mia", points: 0 };
player.points += 10;
player.level = 2;          // new property
console.log(player);

Objects with functions

An object can also contain functions – then they’re called methods:

const counter = {
  count: 0,
  plus() {
    this.count++;
  },
};

counter.plus();
counter.plus();
console.log(counter.count);

this means “this object itself” – like self in Python.

Arrays of objects

It gets really powerful when you combine both – this is what real data looks like:

const classroom = [
  { name: "Ana", mark: 2 },
  { name: "Ben", mark: 1 },
  { name: "Cem", mark: 3 },
];

for (const kid of classroom) {
  console.log(`${kid.name}: ${kid.mark}`);
}
console.log(classroom.filter((k) => k.mark <= 2).map((k) => k.name));

Quick check

What does this program print?

const car = { brand: "Kiwi", km: 100 };
car.km += 50;
console.log(car.brand.length, car.km);

Your task

Your turn

Write the function best(players). It gets an array of objects like { name: "Ana", points: 12 } and returns the name of the player with the most points.

function best(players) {
}

const list = [
  { name: "Ana", points: 12 },
  { name: "Ben", points: 30 },
  { name: "Cem", points: 7 },
];
console.log(best(list));

Solve it without hints to earn a ⭐ on your progress page.

Show solution

Try it yourself first – mistakes teach you the most. Here is one possible solution:

function best(players) {
  let top = players[0];
  for (const p of players) {
    if (p.points > top.points) {
      top = p;
    }
  }
  return top.name;
}

const list = [
  { name: "Ana", points: 12 },
  { name: "Ben", points: 30 },
  { name: "Cem", points: 7 },
];
console.log(best(list));