An array was a “numbered shelf.” But when you want to hold a name, a place, and a favorite thing—different kinds of information—managing them by number gets hard. That’s where the object comes in: a drawer where every value carries a name label.
Why an array is awkward here
const shima = ["Shima", "Snowland", "drawing"];
console.log(shima[1]);Nothing about shima[1] tells you what it holds. With an object, you can write:
const shima = {
name: "Shima",
from: "Snowland",
like: "drawing"
};
console.log(shima.from);shima.from—you can read it and know it’s where they live.
The rules for writing one
const shima = {
name: "Shima",
age: 3
};| Part | Meaning |
|---|---|
{ } | The container for the whole drawer (an array’s [ ]) |
name | The key—the label’s name |
: | The separator between label and contents |
"Shima" | The value—the contents |
, | The separator before the next label |
You choose the key names yourself. Values can be text, numbers, even arrays.
Reading and changing
To read, join them with a dot.
console.log(shima.name);
console.log(shima.age);To change, use the same shape with an =.
shima.age = 4;
console.log(shima.age);You can also add a new label later.
shima.hobby = "walks";As with arrays, an object made with const can still have its contents changed (what’s forbidden is swapping the whole drawer for a different one).
Array or object?
| Array | Object | |
|---|---|---|
| Shape | ["A", "B", "C"] | { name: "A", age: 3 } |
| How you read it | By number ([0]) | By label (.name) |
| Good for | The same kind of thing, repeated | Different facts about one thing |
| Example | A list of favorites, a list of scores | A profile, settings, one product |
When unsure, ask whether the order carries meaning. If it does, use an array; if you’d rather call things by name, use an object.
They combine nicely
An object can hold an array:
const shima = {
name: "Shima",
likes: ["drawing", "ramen", "games"]
};
console.log(shima.likes[0]);
console.log(shima.likes.length);shima.likes gets you the shelf, then [0] takes one off it—read it left to right and it makes sense.
Summary of this lesson
- An object is
{ key: value, … }—a labeled drawer - Read with
name.key. Changing and adding use the same shape - Repeated things of one kind go in an array; facts about one thing go in an object