Objects: A First Look
An object groups related values together under names, which is how almost all real data in a program is shaped.
An object holds key-value pairs. Read with dot notation, or with brackets when the key is in a variable. Reading a missing key gives undefined rather than an error.
EXERCISE
1Grouping Related Values Under One Name
Separate variables for related facts fall apart quickly, and an object is the fix that every real program uses.
When several values all describe the same thing, keeping them in separate variables hides that they belong together. Nothing in the code connects userName to userAge except that you happened to name them similarly, so nothing stops one being updated while the other is forgotten, and nothing lets you pass all of them somewhere as a single unit.
The problem:
let userName = "Ada";
let userAge = 36;
let userCity = "London";
// Now store a second user...
let user2Name = "Grace";
let user2Age = 45;
let user2City = "New York";
// Six variables for two people. A hundred users would be unthinkable.
The fix, which is an object:
const user = {
name: "Ada",
age: 36,
city: "London",
};
const user2 = {
name: "Grace",
age: 45,
city: "New York",
};
// Two variables. Each one carries everything about one person.
The anatomy of the syntax:
const book = {
title: "Dune", // key: value, then a comma
pages: 412, // values can be any type
inStock: true,
author: { name: "Frank Herbert" }, // including another object
tags: ["sci-fi", "classic"], // and arrays
};
console.log(typeof book); // object
An object answers the question "what do I know about this one thing?". The moment you notice two or three variables whose names share a prefix, that prefix is telling you they belong in an object together. This is the single most useful shape in , and everything from a row to an response arrives as one.
EXERCISE
2Reading and Writing Properties
There are two ways to reach inside an object, and knowing when each one is required saves a lot of confusion later.
Dot notation is the everyday one:
const user = { name: "Ada", age: 36 };
console.log(user.name); // Ada
console.log(user.age); // 36
user.age = 37; // write
user.city = "London"; // add a property that did not exist
console.log(user); // { name: 'Ada', age: 37, city: 'London' }
Note that you can add properties to an object declared with const. The const protects the label, not the contents.
Bracket notation is required in two cases:
const user = { name: "Ada", "favourite colour": "teal" };
// 1. When the key is not a valid variable name:
console.log(user["favourite colour"]); // teal
// console.log(user.favourite colour); // SyntaxError
// 2. When the key is in a variable, decided while running:
const field = "name";
console.log(user[field]); // Ada
console.log(user.field); // undefined <- looked for a key called "field"
That second case is the one that matters. Dot notation asks for a key by that literal name. Brackets evaluate what is inside them first.
Reading a missing key is not an error:
const user = { name: "Ada" };
console.log(user.age); // undefined
console.log(user.age + 1); // NaN <- the error shows up later
console.log(user.pet.name); // TypeError: Cannot read properties of undefined
// Guard with optional chaining:
console.log(user.pet?.name); // undefined, no crash
Pro Tip: Use dots unless you cannot. Reach for brackets when the key has spaces or dashes, or when the key itself is a value your program worked out. And remember that a missing property gives
undefinedquietly, so the crash usually happens one line later when you try to use it.
EXERCISE
3Objects Hold Functions Too
A function stored on an object is called a method, and it is how an object gains behaviour as well as data.
You have already used methods. "hello".toUpperCase() is a method on a string. You can write your own.
A function stored as a property:
const calculator = {
total: 0,
add: function (n) {
calculator.total = calculator.total + n;
},
};
calculator.add(5);
calculator.add(3);
console.log(calculator.total); // 8
The shorthand everyone uses now:
const greeter = {
greeting: "Hello",
// Shorthand: drop the colon and the word function
welcome(name) {
return `${this.greeting}, ${name}!`;
},
};
console.log(greeter.welcome("Ada")); // Hello, Ada!
this refers to the object the method was called on. It has real subtleties, and Intermediate JavaScript covers them properly. For now, inside a method written this way, this is the object.
Why this shape is everywhere:
// The built-in objects you already use are exactly this shape.
console.log(Math.max(3, 9, 1)); // 9 max is a method on Math
console.log(Math.round(4.6)); // 5
console.log(JSON.stringify({ a: 1 })); // {"a":1}
// Data and the operations on that data, kept together.
Keeping a function next to the data it works on is the whole idea behind objects as a tool rather than just a . When you find yourself passing the same object into three different functions, that is a strong hint those functions want to be methods on it instead.
