Lesson 8
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 }.
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...
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"{ } (this is called an object literal).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.
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.
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 }There are two ways to read the value of a property:dot notation and bracket notation.
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); // undefinedBrackets are particularly useful when the property name is only known at runtime, for example because it comes from user input or from a loop:
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.
An object is dynamic: you can modify its properties, add new ones or delete some at any time.
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 person = { name: "Martin" };
person.name = "Bernard"; // allowed: we modify the content
person = { name: "Bernard" }; // TypeError: you cannot reassign a constIf 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).
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" } → unchangedObject.freeze is "shallow": nested objects inside are not frozen.
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.
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.5object.method().this lets a method read or modify the properties of the object it belongs to.=>) 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:
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"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.
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: 12There 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.
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:
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 }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"in operator tests for the presence of a key, even if its value is undefined.?. stops the evaluation and returns undefined if part of the path does not exist, instead of causing an error.?? 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:
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)The value of a property can itself be an object or an array. This lets you represent complex data by chaining accesses.
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); // 3You modify a nested value in the same way, by following the path to the desired property:
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 lets you extract several properties from an object in a single line, into separate variables. It is very widely used in modern JavaScript.
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:
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"As with arrays, the ... (spread) operator lets you copy an object or merge several objects without modifying the originals.
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.
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 versionObjects 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.
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.
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" → unchangedThe 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 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 31In 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.
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.
// 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 intactJSON (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.
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.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:
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));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.
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 1Arrays 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.
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.
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()); // 95Here 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.
undefined or null object: user.contact.phone causes an error if contact does not exist. Use ?. to protect yourself.const b = a copies the object: both variables then refer to the same object.product.key (literal key) and product[key] (key contained in a variable).=== thinking you are comparing their content: only the reference is compared.this: this will not refer to the object.forEach directly on an object: you must first go through Object.keys, Object.values or Object.entries.JSON.parse requires double quotes.birthDate rather than bd or birth_date.?. and ?? whenever a piece of data may be missing (server response, user input...).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:
available set to true, then modify the price.description() that returns a sentence like "Title, by Author (year)" using this.Object.entries with for...of to display all the properties of the book (except the method).filter to keep only those under $30, map to get the list of their titles, and reduce to calculate the total price.Exercise 2: destructuring and optional chaining
Here is an object: const student = { name: "Aina", classroom: { level: "Grade 12", room: 12 } };
name and level into two variables.student.teacher?.name without causing an error."Not provided" using the ?? operator.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:
reduce.JSON.stringify, then convert it back with JSON.parse and check the content.object.key) or with brackets (object["key"]).this refers to the current object inside it.Object.keys, Object.values and Object.entries let you loop through an object.structuredClone (deep copy).map, filter, find and reduce.JSON.stringify and JSON.parse convert an object into JSON text and back.?. and the ?? operator protect your code against missing properties.