Functions, Arrays and Objects
Functions
function add(a, b) {
return a + b;
}
const multiply = (a, b) => a * b; // arrow function
const square = n => n * n; // one parameter, implicit return
function greet(name = "friend") { // default parameter
return `Hello, ${name}!`;
}
function sum(...numbers) { // rest parameter
return numbers.reduce((acc, n) => acc + n, 0);
}
Functions are values: you can store them, pass them and return them.
Arrays
const tasks = ["plan", "build"];
tasks.push("ship"); // add to end
tasks.includes("build"); // true
tasks.indexOf("ship"); // 2
tasks.length;
The three methods you will use constantly:
const products = [
{ name: "Hoodie", cents: 3900, inStock: true },
{ name: "Mug", cents: 1250, inStock: false },
{ name: "Cap", cents: 1800, inStock: true },
];
const names = products.map(p => p.name); // transform
const available = products.filter(p => p.inStock); // select
const totalCents = products.reduce((sum, p) => sum + p.cents, 0); // combine
const cheapest = [...products].sort((a, b) => a.cents - b.cents)[0];
const hasMug = products.some(p => p.name === "Mug");
const found = products.find(p => p.cents > 3000);
sort changes the original array, so copy it first with [...array] (or use toSorted() in modern browsers).
Objects
const user = {
name: "Ada",
role: "admin",
greet() { return `Hi, I am ${this.name}`; },
};
user.email = "ada@example.com";
user["role"];
Object.keys(user);
Object.entries(user).forEach(([key, value]) => console.log(key, value));
Destructuring and spread
const { name, role = "user" } = user; // pull out properties
const [first, ...rest] = tasks; // pull out array items
const updated = { ...user, role: "editor" }; // copy with a change
const allTasks = [...tasks, "celebrate"]; // copy with an addition
Spreading creates shallow copies. Nested objects are still shared; use structuredClone(obj) for a deep copy.
JSON
const text = JSON.stringify({ id: 1, tags: ["js"] }); // to string
const data = JSON.parse(text); // back to object
Exercise
Given an array of order objects ({ id, customer, items: [{ cents, qty }] }), compute each order's total with map and reduce, keep orders over $50 with filter, and log the customer names sorted alphabetically.
Check yourself
- What does
mapreturn compared withforEach? - Why copy an array before calling
sort? - What does
{ ...user, role: "editor" }create?
Votre progression est enregistrée dans ce navigateur uniquement.
Envoyer pour relecture (10 points)