All lessons

Objects

8 min · JavaScript

Store values under named keys instead of numbered positions.

JavaScript · Objects0/5 cleared

Enemy 1 of 5

This code makes an object with a name and a score, then prints the name by its key using player.name. Press Run to see it.

Why this works

Arrays are great for ordered collections you look up by numeric position, but a lot of real data is more naturally described by name than by position. An object holds key-value pairs inside curly braces { }: each value is looked up by a meaningful name (its key) rather than an index.

You can read a value two ways: dot notation (player.name) is the shorter, more common form when you already know the key name; bracket notation (player["name"]) works the same way but is required when the key is stored in a variable or contains characters that aren't valid in dot notation (like a space).

Think of an object as describing "one thing with several properties" (a player has a name and a score, a car has a make and a model), whereas an array is better suited to "many things of the same kind in a row." Real programs frequently combine both: an array of player objects, for instance.

You
Cargo Cultist
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.