Objects — JavaScript

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…

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

There are two ways to read a property:

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

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 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

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 inside student, then called with student.greet(). Inside a method, this means the object that owns the method, here student. In a plain function like nameCard, this doesn'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

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.

What you will learn