Lesson 2 · Unit 04
Objects and their types
Named values, and shapes the compiler checks
What you practise
- Object literals,
typeandinterface, optional properties, nesting, destructuring, spread, the misspelt property the compiler catches
Try a question from this lesson
Pick one
Curly brackets can group values and give each one a name. What do you think this prints?
const pet = { name: "Rex", age: 3 };
console.log(pet.age);Correct answer
3
Why
This is an object: two values kept together, each under a name. The names are called properties. A dot followed by the property name reads its value, so pet.age is 3. An array numbers its items. An object names them.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Objects
An object groups values that belong together. Each value has a name, its property. Write name: value pairs in curly brackets, with commas between them.
Read a property with a dot, and change it by storing into it.
The compiler works out the type of the object: here, a name that is a string and an age that is a number.
const pet = { name: "Rex", age: 3 };
pet.age = 4; // change
console.log(pet.name); // Rex
console.log(pet.age); // 4Concept
Naming a shape
type gives the shape of an object a name. After that, the name works as a type, like number or string.
A variable annotated with Pet must hold an object with exactly these properties, each of the right type.
interface Pet { ... } does the same job for objects. You will meet both.
type Pet = {
name: string;
age: number;
};
const rex: Pet = { name: "Rex", age: 3 };
const tom: Pet = { name: "Tom", age: 7 };
console.log(rex.name, tom.age); // Rex 7Concept
Destructuring and spread
Destructuring pulls properties out into variables of the same name, in one line.
Spread, written as three dots, copies all the properties of an object into a new object. Properties written after it replace the copied ones.
Spread gives you a changed copy. The original object stays as it was.
const user = { name: "Ada", age: 36 };
const { name, age } = user;
console.log(name, age); // Ada 36
const older = { ...user, age: 37 };
console.log(older.age); // 37
console.log(user.age); // 369 more exercises in the app
- 3× multiple choice
- 1× fill the blanks
- 3× type the answer
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.