So far most of your variables have held one thing: a number, a string, a boolean. Real-world things have many details. A student has a name, a grade, an ID, and a schedule. An object bundles all of those details together under one name.
// Without objects: loose variables that only belong together by naming
let studentName = "Riley";
let studentGrade = 10;
let studentGPA = 3.6;
// With an object: one thing, with named parts
const student = {
name: "Riley",
grade: 10,
gpa: 3.6
};
console.log(student.name);
Now you can pass the whole student to a function, store thirty students in a list, or add a new detail without inventing another variable name.
You have been using objects all along without writing your own:
console.log("...") // console is an object; log is one of its methods
Math.PI // Math is an object; PI is one of its properties
document.getElementById // the whole web page is an object called document
const car = {
make: "Toyota", // a PROPERTY: key "make", value "Toyota"
year: 2021, // another property
honk() { // a METHOD: a property whose value is a function
return "Beep!";
}
};
| Key | The name of a detail (make) |
| Value | What is stored under that name ("Toyota") |
| Property | A key and its value together |
| Method | A property that holds a function: something the object can do |
An object is like a filled-in form. The labels on the form are the keys ("Name:", "Year:"). What is written in each box is the value. Methods are the instructions printed at the bottom ("To honk, press here").
| Lesson | Question it answers |
|---|---|
| Object Intro | How do I create one? |
| Object Properties | How do I read, add, change, and remove details? |
| Object Methods | How do I give an object actions? |
| Object this | How does a method refer to its own object? |
| Object Display | How do I show an object's contents? |
| Object Constructors | How do I make many objects of the same shape? |
Objects go much deeper than this section. So the names are familiar when you meet them later, the advanced path covers:
Object.assign(), Object.create(), and Object.fromEntries()In const car = { make: "Toyota", honk() { return "Beep!"; } };, what is honk?
make is a key, and "Toyota" is its value.Which of these is not an object?
42Why use one object instead of separate variables like studentName, studentGrade?
book.titleMath.PI, then log Math.round(4.6). Which one is a property and which is a method?