Objects
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Objects group related data
- An object stores named values together:
{ key: value, ... }. - Reach a value by its key with a dot:
person.name. - An object is perfect for one thing that has several details.
let person = { name: "Ada", age: 36 };
console.log(person.name); // → Ada
console.log(person.age); // → 36
Explore
A key looks up a value
An object maps each key to a value. obj.key looks one up instantly.
Change or add a property
- Assign to
obj.keyto change a value — or to add a brand-new one.
let car = { speed: 0 };
car.speed = 60; // change an existing key
car.colour = "red"; // add a new key
console.log(car.speed); // → 60
Watch out
- A missing key gives
undefined, not an error:person.height→undefined. person["name"]does the same asperson.name— handy when the key sits in a variable.
Common mistakes
- Read a value with
obj.keyorobj["key"]. - A missing key gives
undefined, not an error.
Now you try
- Read and change object properties.
- Press Check answer to test it.
let book = { title: "CS", pages: 200 }. Log the book's title with book.title (it is CS).
Click Run to see the output here.
let car = { speed: 0 }. Change car.speed to 80, then log it.
Click Run to see the output here.
Create an object p with a property x set to 3 and a property y set to 4.
Click Run to see the output here.