Lesson 8 / 1080%

Lesson 8

Objects

22 min

Structure data with properties and methods.

Definition

An object is a data structure that groups several related pieces of information in a single variable, in the form ofkey: value pairs called properties. Each key is a name that identifies a value, and that value can be of any type, including a function, in which case it is called amethod. An object is created with curly braces:{ key: value }.

What is an object in JavaScript?

An object is a data structure that groups several related pieces of information in a single variable. Where an array stores an ordered list of values accessible by their index, an object stores data as key: value pairs, calledproperties. It is ideal for describing "something" from the real world: a user, a product, a car...

creation.js
const user = {
  lastName: "Dupont",
  firstName: "Pierre",
  age: 25,
  isLoggedIn: true,
};

console.log(user.lastName);  // "Dupont"
console.log(user.age);       // 25
console.log(typeof user);    // "object"
  • An object is declared with curly braces { } (this is called an object literal).
  • Each property is made of a key (its name) and a value (of any type: string, number, boolean, array, another object, function...).
  • Properties are separated by commas.

To picture an object, think of an ID card: it has fields (last name, first name, date of birth) and, for each one, a piece of information. The fields are the keys, the pieces of information are the values. Without objects, you would have to create a separate variable for each piece of information (userName,userAge, userCity...), which quickly becomes unreadable as soon as you handle several users.

Object or array: which one to choose?

  • Use an array for a list of items of the same kind where the order matters (grades, first names, prices).
  • Use an object to describe a single thing with several named characteristics (a user, a product).
  • To handle several described things, combine both: an array of objects, which we will see later.

Creating an empty object and using shorthand notation

You can create an empty object and fill it in later. When the name of a variable is identical to the desired key name, you can also write the key only once: this is the shorthand notation.

empty-object-and-shorthand.js
const empty = {};
empty.title = "My first object";
console.log(empty); // { title: "My first object" }

const name = "Dupont";
const age = 25;

// Long version
const person1 = { name: name, age: age };

// Shorthand notation (equivalent)
const person2 = { name, age };

console.log(person2); // { name: "Dupont", age: 25 }

Accessing properties

There are two ways to read the value of a property:dot notation and bracket notation.

access.js
const product = {
  name: "Keyboard",
  price: 45, // in $
  "in-stock": true,
};

// Dot notation (the most common)
console.log(product.name);   // "Keyboard"

// Bracket notation
console.log(product["price"]);    // 45
console.log(product["in-stock"]); // true (mandatory here because of the hyphen)

// Brackets let you use a variable as a key
const key = "name";
console.log(product[key]); // "Keyboard"

// A non-existent property returns undefined
console.log(product.color); // undefined
  • Prefer dot notation: it is more readable.
  • Use brackets when the key is stored in a variable or contains special characters (space, hyphen...).

Brackets are particularly useful when the property name is only known at runtime, for example because it comes from user input or from a loop:

dynamic-access.js
const priceByFruit = { apple: 2, banana: 1.5, kiwi: 3 };

const choice = "banana"; // could come from a prompt() or a menu
console.log(priceByFruit[choice]); // 1.5

// We can also loop over an array of keys
const basket = ["apple", "kiwi"];
for (const fruit of basket) {
  console.log(fruit, "costs", priceByFruit[fruit], "$");
}

Classic trap

product.key looks for a property literally named "key", whereas product[key] uses thevalue of the variable key. Mixing the two up is one of the most frequent mistakes with objects.

Modifying, adding and deleting properties

An object is dynamic: you can modify its properties, add new ones or delete some at any time.

modification.js
const car = {
  brand: "Toyota",
  year: 2018,
};

car.year = 2020;          // modify an existing property
car.color = "red";        // add a new property
delete car.brand;         // delete a property

console.log(car);
// { year: 2020, color: "red" }

Be careful: declaring an object with const does not prevent modifying its content. const only forbidsreassigning the variable to another object.

const-object.js
const person = { name: "Martin" };

person.name = "Bernard";        // allowed: we modify the content
person = { name: "Bernard" };   // TypeError: you cannot reassign a const

If you really want to prevent any modification of an object, you can "freeze" it with Object.freeze(). Attempts to modify it are then ignored (or cause an error in strict mode).

freeze.js
const config = Object.freeze({ language: "en", theme: "light" });

config.language = "fr"; // silently ignored
config.version = 2;     // also ignored
console.log(config);    // { language: "en", theme: "light" } → unchanged

Object.freeze is "shallow": nested objects inside are not frozen.

Methods: functions inside an object

When the value of a property is a function, it is called a method. It can access the other properties of the object thanks to the this keyword, which refers to the current object.

methods.js
const student = {
  firstName: "Camille",
  grades: [12, 15, 9, 18],

  introduce() {
    console.log("Hello, my name is " + this.firstName);
  },

  average() {
    const total = this.grades.reduce((sum, n) => sum + n, 0);
    return total / this.grades.length;
  },
};

student.introduce();              // "Hello, my name is Camille"
console.log(student.average());   // 13.5
  • A method is called with parentheses: object.method().
  • this lets a method read or modify the properties of the object it belongs to.
  • Avoid arrow functions (=>) to define a method that uses this: they do not bind to the object the way the classic syntax does.

A method can also modify the object it belongs to. This is what lets you group data and the actions that concern it in the same place:

modifying-method.js
const account = {
  owner: "Léa",
  balance: 100,

  deposit(amount) {
    this.balance += amount;
  },

  withdraw(amount) {
    if (amount > this.balance) {
      console.log("Insufficient balance");
      return;
    }
    this.balance -= amount;
  },
};

account.deposit(50);
account.withdraw(30);
console.log(account.balance); // 120
account.withdraw(500);        // "Insufficient balance"

Looping through an object

Unlike arrays, an object has no forEach method. You use the methods of Object to get its keys, its values or both, as an array.

looping.js
const product = { name: "Keyboard", price: 45, stock: 12 };

Object.keys(product);    // ["name", "price", "stock"]
Object.values(product);  // ["Keyboard", 45, 12]
Object.entries(product); // [["name", "Keyboard"], ["price", 45], ["stock", 12]]

// Loop over key + value with for...of
for (const [key, value] of Object.entries(product)) {
  console.log(key + ": " + value);
}
// name: Keyboard
// price: 45
// stock: 12

There is also the for...in loop, which goes through the keys of an object. It works, but Object.entries is generally preferred because it is more explicit and safer.

for-in.js
const product = { name: "Keyboard", price: 45 };

for (const key in product) {
  console.log(key, "→", product[key]);
}

Since these methods return arrays, you can applymap, filter orreduce to them. To count the properties of an object (it has no length), you use the length of the array of its keys:

advanced-looping.js
const grades = { math: 14, french: 11, history: 16 };

// Number of properties
console.log(Object.keys(grades).length); // 3

// Average of the values
const values = Object.values(grades);
const average = values.reduce((total, n) => total + n, 0) / values.length;
console.log(average); // 13.666...

// Rebuild an object from key/value pairs
const boosted = Object.fromEntries(
  Object.entries(grades).map(([subject, grade]) => [subject, grade + 1])
);
console.log(boosted); // { math: 15, french: 12, history: 17 }

Checking that a property exists

existence.js
const user = { name: "Dupont", address: { city: "Paris" } };

"name" in user;                 // true
"email" in user;                // false
Object.hasOwn(user, "name");    // true

// Optional chaining (?.): avoids errors on missing properties
console.log(user.address.city);          // "Paris"
console.log(user.contact?.phone);        // undefined (no error!)
// console.log(user.contact.phone);      // TypeError: contact is undefined

// Default value with ??
const phone = user.contact?.phone ?? "Not provided";
console.log(phone); // "Not provided"
  • The in operator tests for the presence of a key, even if its value is undefined.
  • Optional chaining ?. stops the evaluation and returns undefined if part of the path does not exist, instead of causing an error.
  • The ?? operator provides a default value when the left-hand value is null or undefined.

Optional chaining also works for calling a method that may not exist, or for reading an array element that may not be defined:

advanced-optional-chaining.js
const user = { name: "Dupont", friends: ["Léa", "Tom"] };

console.log(user.friends?.[0]);         // "Léa"
console.log(user.favorites?.[0]);       // undefined (favorites does not exist)
console.log(user.introduce?.());        // undefined (the method does not exist)

Nested objects

The value of a property can itself be an object or an array. This lets you represent complex data by chaining accesses.

nested.js
const company = {
  name: "TechParis",
  address: {
    city: "Paris",
    country: "France",
  },
  employees: ["Pierre", "Julie", "Camille"],
};

console.log(company.address.city);       // "Paris"
console.log(company.employees[1]);       // "Julie"
console.log(company.employees.length);   // 3

You modify a nested value in the same way, by following the path to the desired property:

nested-modification.js
company.address.city = "Lyon";          // modify a nested value
company.employees.push("Antoine");      // add to a nested array
company.address.postalCode = "69001";   // add a nested property

console.log(company.address);
// { city: "Lyon", country: "France", postalCode: "69001" }

Destructuring

Destructuring lets you extract several properties from an object in a single line, into separate variables. It is very widely used in modern JavaScript.

destructuring.js
const user = { name: "Dupont", age: 25, city: "Lyon" };

// Without destructuring
const name1 = user.name;
const age1 = user.age;

// With destructuring
const { name, age } = user;
console.log(name, age); // "Dupont" 25

// Rename a variable and give a default value
const { city: town, country = "France" } = user;
console.log(town, country); // "Lyon" "France"

// Very handy in a function's parameters
function display({ name, age }) {
  console.log(name + " is " + age + " years old");
}
display(user); // "Dupont is 25 years old"

Destructuring also works on nested objects, and with the "rest" syntax (...) to collect "all the rest" of the properties in a new object. Arrays are destructured in the same way, with square brackets:

advanced-destructuring.js
const company = {
  name: "TechParis",
  address: { city: "Paris", country: "France" },
  employees: 120,
  founded: 2010,
};

// Nested object
const { address: { city } } = company;
console.log(city); // "Paris"

// Rest: we isolate some properties and keep the rest
const { name, ...others } = company;
console.log(name);    // "TechParis"
console.log(others);  // { address: {...}, employees: 120, founded: 2010 }

// Array destructuring (by position)
const [first, second] = ["red", "green", "blue"];
console.log(first, second); // "red" "green"

Copying and merging objects with spread

As with arrays, the ... (spread) operator lets you copy an object or merge several objects without modifying the originals.

spread.js
const base = { name: "Dupont", age: 25 };

// Copy
const copy = { ...base };

// Copy with a modification
const older = { ...base, age: 26 };

// Merging several objects (the last one wins in case of conflict)
const full = { ...base, city: "Lyon", age: 30 };

console.log(base);   // { name: "Dupont", age: 25 } → unchanged
console.log(full);   // { name: "Dupont", age: 30, city: "Lyon" }

This technique is widely used to "update" an object without modifying it directly: you create a new version with the desired changes, and keep the old one intact. It is the basis of data management in libraries such as React.

immutable-update.js
const profile = { name: "Léa", theme: "light", language: "en" };

const darkProfile = { ...profile, theme: "dark" };

console.log(profile.theme);      // "light" → the original is intact
console.log(darkProfile.theme);  // "dark"  → new version

Objects and references: a classic trap

Objects are reference types: a variable does not contain the object itself, but a reference to it in memory. Assigning an object to another variable therefore doesnot create a copy.

references.js
const a = { value: 1 };
const b = a; // b points to the SAME object as a

b.value = 99;
console.log(a.value); // 99 → a was modified too!

// To create a real copy:
const c = { ...a };
c.value = 5;
console.log(a.value); // 99 → a is not affected

// Two objects with identical content are not equal
console.log({ x: 1 } === { x: 1 }); // false (two different references)

Spread makes a shallow copy: nested objects remain shared between the original and the copy. For a complete copy, usestructuredClone.

deep-copy.js
const original = { name: "Dupont", address: { city: "Lyon" } };

const shallow = { ...original };
shallow.address.city = "Marseille";
console.log(original.address.city); // "Marseille" → modified too!

const deep = structuredClone(original);
deep.address.city = "Toulouse";
console.log(original.address.city); // "Marseille" → unchanged

The same behavior applies when you pass an object to a function: the function receives the reference, and can therefore modify the original object without you intending it.

function-references.js
function ageUp(person) {
  person.age++; // modifies the original object!
}

const lea = { name: "Léa", age: 20 };
ageUp(lea);
console.log(lea.age); // 21

// Version without side effects: we return a new object
const ageUpSafely = (person) => ({ ...person, age: person.age + 1 });
const tom = { name: "Tom", age: 30 };
const olderTom = ageUpSafely(tom);
console.log(tom.age, olderTom.age); // 30 31

Arrays of objects: the most common case

In real applications, data is almost always stored as anarray of objects (a list of products, users, articles...). This is where the map,filter, find andreduce methods from the arrays lesson really make sense.

array-of-objects.js
const products = [
  { id: 1, name: "Keyboard", price: 45, stock: 10 },
  { id: 2, name: "Mouse", price: 25, stock: 0 },
  { id: 3, name: "Monitor", price: 350, stock: 4 },
];

// Get only the names
const names = products.map((p) => p.name);
// ["Keyboard", "Mouse", "Monitor"]

// Keep the products in stock
const available = products.filter((p) => p.stock > 0);

// Find a product by its id
const monitor = products.find((p) => p.id === 3);
console.log(monitor.name); // "Monitor"

// Calculate the total value of the stock
const stockValue = products.reduce((total, p) => total + p.price * p.stock, 0);
console.log(stockValue); // 1850 ($)

// Sort by descending price (without modifying the original)
const byPrice = [...products].sort((a, b) => b.price - a.price);

A few other common operations on an array of objects: sorting by text, checking a condition across all the objects, and "updating" a single object without modifying the others.

advanced-array-of-objects.js
// Sort in alphabetical order of the name
const byName = [...products].sort((a, b) => a.name.localeCompare(b.name));

// Is at least one product out of stock?
const hasOutOfStock = products.some((p) => p.stock === 0);
console.log(hasOutOfStock); // true

// Do all the products cost less than 500?
const allAffordable = products.every((p) => p.price < 500);
console.log(allAffordable); // true

// Update the stock of product 2, without modifying the others
const updated = products.map((p) =>
  p.id === 2 ? { ...p, stock: 15 } : p
);
console.log(updated[1].stock);  // 15
console.log(products[1].stock); // 0 → the original array is intact

Objects and the JSON format

JSON (JavaScript Object Notation) is a text format, very close to the syntax of JavaScript objects, used to exchange data between a server and a web application. Two methods let you go from an object to JSON and back.

json.js
const user = { name: "Dupont", age: 25, active: true };

// Object → JSON text
const json = JSON.stringify(user);
console.log(json); // '{"name":"Dupont","age":25,"active":true}'

// JSON text → object
const object = JSON.parse(json);
console.log(object.name); // "Dupont"
  • JSON.stringify converts an object into a string, ready to be sent or stored.
  • JSON.parse converts a JSON string back into a usable JavaScript object.
  • In JSON, keys must be enclosed in double quotes, and functions are not supported.

Malformed JSON causes an error during JSON.parse. When the text comes from outside (a server, a file, user input), it is wise to protect the call with try / catch. The optional second and third arguments of JSON.stringify also let you get an indented, more readable output:

advanced-json.js
const text = '{ name: "Dupont" }'; // invalid: the key has no quotes

try {
  const object = JSON.parse(text);
  console.log(object);
} catch (error) {
  console.log("Invalid JSON:", error.message);
}

// Indented output with 2 spaces
const user = { name: "Dupont", age: 25 };
console.log(JSON.stringify(user, null, 2));

The built-in objects you already use

Without knowing it, you have been handling objects since the beginning of this course. JavaScript provides many predefined objects, which group ready-to-use properties and methods.console is an object of which log is a method, and Math is an object that gathers mathematical functions.

built-in-objects.js
console.log("Hello");           // log is a method of the console object

console.log(Math.PI);           // 3.141592653589793 (a property)
console.log(Math.round(4.6));   // 5   (rounding)
console.log(Math.max(3, 9, 5)); // 9   (the largest)
console.log(Math.floor(4.9));   // 4   (round down)

const today = new Date();            // an object that represents the date and time
console.log(today.getFullYear());    // the current year

console.log(Math.random()); // a random number between 0 and 1

Arrays and strings also behave like objects:"text".length is a property, and"text".toUpperCase() is a method. This is why the same dot notation is used everywhere in JavaScript.

In practice: managing a shopping cart

Let's put together everything we have just seen in a concrete example: a cart represented by an object that contains anarray of objects and methods to manipulate it.

cart.js
const cart = {
  customer: "Léa",
  items: [],

  add(name, price, quantity = 1) {
    this.items.push({ name, price, quantity });
  },

  total() {
    return this.items.reduce(
      (sum, item) => sum + item.price * item.quantity,
      0
    );
  },

  summary() {
    const lines = this.items.map(
      (i) => i.quantity + " x " + i.name + " = " + i.price * i.quantity
    );
    return lines.join(" | ");
  },
};

cart.add("Keyboard", 45);
cart.add("Mouse", 25, 2);

console.log(cart.summary()); // "1 x Keyboard = 45 | 2 x Mouse = 50"
console.log(cart.total());   // 95

Here you find the shorthand notation ({ name, price, quantity }), a default value, this, reduce,map and join: all the notions of the course combined in a few lines.

Common mistakes with objects

  • Reading a property of an undefined or null object: user.contact.phone causes an error if contact does not exist. Use ?. to protect yourself.
  • Believing that const b = a copies the object: both variables then refer to the same object.
  • Mixing up product.key (literal key) and product[key] (key contained in a variable).
  • Comparing two objects with === thinking you are comparing their content: only the reference is compared.
  • Using an arrow function for a method that relies on this: this will not refer to the object.
  • Forgetting the comma between two properties, or adding one too many, which causes a syntax error.
  • Calling forEach directly on an object: you must first go through Object.keys, Object.values or Object.entries.
  • Writing keys without quotes in JSON: JSON.parse requires double quotes.

Best practices for working with objects

  • Use explicit and consistent keys, in camelCase: birthDate rather than bd or birth_date.
  • Group in a single object the information that describes the same thing, rather than multiplying separate variables.
  • Prefer creating a new version of an object with spread rather than modifying the original, especially when it is shared between several parts of the code.
  • Use destructuring to extract only the properties you need, notably in function parameters.
  • Protect your accesses with ?. and ?? whenever a piece of data may be missing (server response, user input...).
  • Keep the same format for all the objects in an array: same keys, same types of values. This makes the code that loops over them much simpler.

Debugging tip

To inspect an object, use console.log(object): the console lets you expand its properties. To display an array of objects clearly, try console.table(array), which presents it as a table with one column per key.

Exercise 1: working with an object

Create an object book with the propertiestitle, author, year andprice. Then:

  1. Display the title with dot notation, then the author with bracket notation.
  2. Add a property available set to true, then modify the price.
  3. Add a method description() that returns a sentence like "Title, by Author (year)" using this.
  4. Use Object.entries with for...of to display all the properties of the book (except the method).
  5. Create an array of 4 books, then use filter to keep only those under $30, map to get the list of their titles, and reduce to calculate the total price.
  6. Make a copy of your book with spread while changing the price, and check that the original has not been modified.

Exercise 2: destructuring and optional chaining

Here is an object: const student = { name: "Aina", classroom: { level: "Grade 12", room: 12 } };

  1. Using destructuring, extract name and level into two variables.
  2. Display student.teacher?.name without causing an error.
  3. Display the teacher's name or "Not provided" using the ?? operator.
  4. Create a deep copy of the object with structuredClone, change the room in the copy, then check that the original has remained identical.

Exercise 3: managing an inventory

Create an array inventory containing at least five products, each with an id, a name, a priceand a stock. Then:

  1. Display the name of the products that are out of stock.
  2. Calculate the total value of the stock with reduce.
  3. Create a new array where the price of each product is increased by 10%, without modifying the original array.
  4. Convert the result to JSON with JSON.stringify, then convert it back with JSON.parse and check the content.

Key takeaways

  • An object groups data as key: value pairs, declared between curly braces.
  • You access properties with dot notation (object.key) or with brackets (object["key"]).
  • A function stored in an object is called a method, and this refers to the current object inside it.
  • Object.keys, Object.values and Object.entries let you loop through an object.
  • Destructuring and spread make working with objects shorter and more readable.
  • Objects are references: to copy, use spread (shallow copy) or structuredClone (deep copy).
  • In practice, you mostly work with arrays of objects using map, filter, find and reduce.
  • JSON.stringify and JSON.parse convert an object into JSON text and back.
  • Optional chaining ?. and the ?? operator protect your code against missing properties.