Chapter 6 of 14
Functions are reusable blocks of code. They're the core building block of every program — if you find yourself repeating the same code, it should be a function.
// Declaration — can be called before it's defined (hoisted)
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Nelson")); // Hello, Nelson!
// Multiple parameters
function add(a, b) {
return a + b;
}
// Default parameters
function greet(name = "stranger") {
return `Hello, ${name}!`;
}
greet(); // Hello, stranger!
greet("Nelson"); // Hello, Nelson!// Function expression — stored in a variable
const double = function(n) {
return n * 2;
};
// Arrow function — concise syntax (most common in modern JS)
const double = (n) => n * 2; // single expression, implicit return
const square = n => n * n; // one param, no parentheses needed
const add = (a, b) => a + b;
const greet = (name) => { // block body — explicit return needed
const message = `Hello, ${name}!`;
return message;
};
// Arrow functions capture the surrounding 'this'
// (important when working with classes and React)// Rest — collects extra arguments into an array
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3, 4, 5); // 15
// Spread — expands an array/object into individual values
const nums = [1, 2, 3];
console.log(Math.max(...nums)); // 3
const first = [1, 2, 3];
const second = [4, 5, 6];
const all = [...first, ...second]; // [1, 2, 3, 4, 5, 6]TIP
Functions should do one thing. A function called getUserAndSendEmail() is doing two things. Split it: getUser() and sendEmail(user). Functions that do one thing are easier to test, reuse, and understand.