Try storing one student's details: name Sari, age 16, major Humanities. With what you know so far, you need three separate variables: nameSari, ageSari, majorSari. Add one more student and you have six variables. The more students there are, the easier it is to confuse which data belongs to which student.
An object brings related data, such as one student's name, age and major, together in one variable. Each piece of data is stored as a property: a pair of a property name (the key) and its value. An object is like an ID card. One card is one object. The labels on the card, such as "Name" and "Age", are the property names. The detail next to each label is its value.
Making an object and reading its properties
This code makes the object student with three properties, then prints two of them:
const student = {
name: "Sari",
age: 16,
major: "Humanities"
};
console.log(student.name); // Sari
console.log(student["major"]); // Humanities
{opens the object and}closes it.name: "Sari"is one property: the property's name, a colon:(not=), then its value.- A comma
,separates one property from the next. The separator is not a semicolon. The last property may go without a comma. - A property's value can be any type: here there are strings and a number.
- The
;after}marks the end of the wholeconst student = ...instruction.
There are two ways to read a property:
- Dot notation:
student.name. Write the variable's name, a dot, then the property's name. - Bracket notation:
student["major"]. Write the property's name as text inside square brackets, with its quote marks. You must use this form in two cases. First, when the property's name is stored in a variable. Second, when the property's name has a space or a-in it, or starts with a digit.
If you read a property that doesn't exist, the result is undefined, not an error.
But reading a property of undefined is an error. student has no address, so student.address gives undefined. Then student.address.city tries to read city from undefined, and in Chrome it fails with TypeError: Cannot read properties of undefined (reading 'city'). To stop safely, write ?. (optional chaining) in place of the dot:
console.log(student.address?.city); // undefined
console.log(student.address?.city ?? "not given"); // not given
?.givesundefined, with no error, when the value on its left isundefinedornull.??uses the value on its right as a backup value when the value on its left isundefinedornull. The||sign (see the Conditions lesson) is also often used for a backup value, but||also replaces0and""(empty text):0 || 10gives10, while0 ?? 10gives0.
Changing and adding properties
This code changes one property of student and adds a new one:
student.age = 17;
student.city = "Bristol";
console.log(Object.keys(student)); // ["name", "age", "major", "city"]
student.age = 17;changes the value of a property that already exists.student.city = "Bristol";adds a new property, becausestudenthad nocityproperty yet.Object.keys(student)gives an array of all the property names, in the order they were added. The exception: names that are whole numbers (such as"2") always come first, from smallest to largest.- To run the same code for each property, combine
Object.keyswithfor...of(a loop, see the Loops lesson):for (const key of Object.keys(student)) { console.log(key, student[key]); }. Herestudent[key]uses brackets because the property's name is stored in the variablekey.
student was made with const. Why can its contents change? Because const only locks the variable: the variable student can't be given another object. So student = {} (an empty object) is refused with a TypeError, but the contents of the object can still change. One more thing: let and const are only for making new variables. Adding a property does not make a variable, so let student.city = "Bristol" is an error.
An object as a function's input
A function is a group of code lines with a name, and it runs only when it is called. console.log is a function too, but this one you make yourself. A function can take an object and build a result from that object's properties:
function nameCard(person) {
return "Name: " + person.name + ", city: " + person.city;
}
const friend = { name: "Rina", city: "Manchester" };
console.log(nameCard(friend)); // Name: Rina, city: Manchester
function nameCard(person) { ... }makes a function namednameCard. The function's code goes between{and}. Here{ }holds the function's code. It does not make an object.personis a parameter: a name for the value that is sent in when the function is called. Inside the function, you read the properties of the object that was sent in withperson.nameandperson.city.returngives the result back to the line that called the function. The value afterreturnis the function's result.+joins pieces of text. A space inside the quote marks becomes part of the result:"Name: "has a space after the colon.nameCard(friend)calls the function and sends in the objectfriend. So inside the function,personholds the objectfriend.
Take the data only from the parameter. In the exercise, the same function is also called with other people's data. So don't write the object's contents inside the function, and don't type a name like "Rina" right into the result text.
💡 A function written inside an object is called a method. For example
greet() { return "Hi, I'm " + this.name; }written insidestudent, then called withstudent.greet(). Inside a method,thismeans the object that owns the method, herestudent. In a plain function likenameCard,thisdoesn't point at the object you sent in. So in a plain function, use the parameter's name:person.name.
⚠️ Small punctuation that breaks an object
=or;inside an object.{ name = "Budi"; age = 17 }is an error. Write{ name: "Budi", age: 17 }.- Brackets without quotes.
student[name]looks for a variable namedname, not the property"name". Writestudent["name"]. - Extra spaces in the result.
" Hi"with a space in front is not the same as"Hi". Check the spaces at the start and end of every piece of text.
TL;DR: An object keeps related data in one variable. Each piece of data is a property: a name: value pair inside { }, separated by commas. If the object is stored in a variable obj, read a property with obj.name or obj["name"], and change or add a property with obj.city = "Bristol". An object stored in a const variable can still have its contents changed, because const only stops the variable from being given another object. Object.keys(obj) gives a list of its property names. A function (lines of code with a name) can take an object through a parameter, a name for the value sent to the function. If the parameter is person, the function reads a property with person.name, then gives back its result with return.
⚡ One variable, many properties
Write:
const student = {
name: "Sari",
age: 16,
major: "Humanities"
};
Meaning: An object brings related data together in one variable, here one student's data. Each piece of data is stored as a property, written name: value inside { }. Commas separate the properties. Inside an object, : separates the name from the value, not =.
⚡ Two ways to read: a dot and square brackets
Write:
console.log(student.name); // Sari
console.log(student["major"]); // Humanities
Guess first: what does student[name] without quotes look for?
A variable named name, not the property "name". Inside square brackets, the property's name goes in as text, with its quote marks.
Meaning: There are two ways to read a property. Dot notation uses a dot: student.name. Bracket notation uses square brackets and the property's name as text: student["major"]. If the property you read doesn't exist, the result is undefined (no value given yet), not an error.
⚡ const, but the contents can change
Write:
student.age = 17;
student.city = "Bristol";
Guess first: student was made with const. Are these two lines an error?
No. const only locks the variable. Giving student another object, for example student = {}, is refused. But the contents of the object can still change.
Meaning: The first line changes the value of the age property, because that property already exists. The second line adds a new property, because student had no city yet.