Lesson 88 min read

Functions

Wrap your code in a reusable box and call it whenever you need it

What Are Functions?

A function is like a recipe card. You write the instructions once, give it a name, and then you can "cook" that recipe anytime by calling its name. You can also pass in ingredients (called parameters) and get back a finished dish (the return value).

Functions are the backbone of JavaScript. They help you:

  • Avoid repetition — write once, use everywhere
  • Organize code — break big problems into small, named pieces
  • Create abstractions — hide messy details behind a clean name

There are three main ways to create functions in JavaScript: declarations, expressions, and arrow functions.

Three Ways to Create Functions

// 1. Function Declaration — the classic way
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Kai")); // "Hello, Kai!"
// 2. Function Expression — stored in a variable
const double = function(n) {
return n * 2;
};
console.log(double(7)); // 14
// 3. Arrow Function — modern & concise
const triple = (n) => n * 3; // implicit return for single expressions
console.log(triple(5)); // 15
// Arrow with a body (needs explicit return)
const describe = (name, age) => {
let status = age >= 18 ? "adult" : "minor";
return `${name} is a ${status}`;
};
console.log(describe("Mia", 15)); // "Mia is a minor"
Output
Hello, Kai!
14
15
Mia is a minor

Parameters — Default Values & Rest

Default parameters let you set a fallback value in case the caller doesn't provide one. It's like a restaurant that brings you water automatically unless you order something else.

Rest parameters (...args) collect any number of arguments into an array. Super useful when you don't know how many inputs you'll get.

Default & Rest Parameters

// Default parameters
function createUser(name, role = "viewer") {
return { name, role };
}
console.log(createUser("Alex")); // { name: "Alex", role: "viewer" }
console.log(createUser("Alex", "admin")); // { name: "Alex", role: "admin" }
// Rest parameters (...) — gather remaining args into an array
function sum(...numbers) {
let total = 0;
for (let n of numbers) total += n;
return total;
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
// Mixing regular and rest params
function announce(action, ...items) {
console.log(`${action}: ${items.join(", ")}`);
}
announce("Bought", "milk", "bread", "eggs");
Output
{ name: "Alex", role: "viewer" }
{ name: "Alex", role: "admin" }
6
100
Bought: milk, bread, eggs

Functions Are Values — Passing Them Around

In JavaScript, functions are first-class values. That means you can store them in variables, pass them as arguments to other functions, and return them from functions. This is what makes JavaScript so flexible.

A function that takes another function as an argument (or returns one) is called a higher-order function. Each function call gets pushed onto the call stack. You'll see these everywhere — setTimeout, addEventListener, array methods like .map() and .filter().

Functions as Values & Closures Intro

// Passing a function as an argument
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
repeat(3, (i) => console.log(`Step ${i}`));
// Returning a function — this creates a CLOSURE
function createMultiplier(factor) {
return (number) => number * factor;
}
const timesFive = createMultiplier(5);
const timesTen = createMultiplier(10);
console.log(timesFive(3)); // 15
console.log(timesTen(3)); // 30
// The returned function "remembers" the factor!
// This is a closure — more on this in the closures lesson.
// Functions in objects (callbacks)
setTimeout(() => console.log("Delayed!"), 0);
console.log("Immediate!");
Output
Step 0
Step 1
Step 2
15
30
Immediate!
Delayed!
Note: Arrow functions have one key difference from regular functions: they don't have their own 'this'. They inherit 'this' from wherever they were defined. This makes them great for callbacks, but tricky as object methods. When in doubt, if you need 'this', use a regular function.

Quick check

What does this arrow function return: (x) => x * x when called with 4?
ObjectsArray Higher-Order Methods