Codiqo

Learn JavaScript · lesson 29 of 60 · about 7 minutes

Objects and Properties

Give Sam's page a profile card: describe one thing with many named values, and read them with dot and bracket notation.

What you'll learn

  • Write object literals
  • Read properties with . and []
  • Add, change and delete properties

A profile card

Sam's page needs a profile card: Sam's name, role, city and the year Sam started. Four separate variables would work, but they belong together. An object keeps them in one value, profile, and gives each one a name. Visitors can also ask to see one detail, typed into a box, and the page looks it up by that name.

Named values

Arrays store things by position. Objects store them by name. Each entry is a property: a key and a value.

{ name: "Phoebe", level: 3 } has two properties, name and level.

Reading properties

const pet = { name: "Phoebe", species: "penguin", level: 3 };
console.log(pet.name);
console.log(pet["species"]);
const key = "level";
console.log(pet[key]);
console.log(pet.colour);

Output

Phoebe
penguin
3
undefined

Changing objects

Assign to a property to add or change it. delete obj.key removes one. Use brackets when the key is in a variable or has spaces.

Updating

const user = { name: "Ada", coins: 50 };
user.coins += 25;
user.streak = 4;
delete user.name;
console.log(user.coins, user.streak, user.name);

Output

75 4 undefined

Tip

A const object can still change inside: const stops the name from pointing at a different object, not the object's properties from changing.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.