Functions and Scope
Declarations, arrow functions, closures and how scope works.
What you will learn
- Write arrow functions
- Explain closures
- Use default and rest parameters
Functions are values in JavaScript: you can store them in variables, pass them to other functions and return them. That flexibility powers almost every modern pattern, from array methods to React components.
function add(a, b) { // declaration
return a + b;
}
const mul = function (a, b) { return a * b; }; // expression
const sub = (a, b) => a - b; // arrow function
console.log(add(2, 3), mul(2, 3), sub(2, 3));5 6 -1
An arrow function with a single expression returns it implicitly. Arrow functions are the standard for short callbacks.
function greet(name = "friend", ...tags) {
return `Hi ${name} [${tags.join(", ")}]`;
}
console.log(greet());
console.log(greet("Ada", "admin", "dev"));
const area = ({ w, h }) => w * h;
console.log(area({ w: 3, h: 4 }));Hi friend [] Hi Ada [admin, dev] 12
Scope and closures
Variables declared with let or const live inside the nearest { } block. A closure is a function that remembers the variables from where it was created, even after that outer function has returned. It is how you keep private state.
function makeCounter() {
let n = 0;
return () => ++n;
}
const a = makeCounter();
const b = makeCounter();
a(); a();
console.log(a(), b());3 1
Each call to makeCounter creates a separate n, so the two counters do not interfere.
function repeat(times, action) {
for (let i = 0; i < times; i++) action(i);
}
repeat(3, (i) => console.log("run", i));run 0 run 1 run 2
A function with no return gives back undefined. Also, a return followed by a newline before the value returns undefined; keep the value on the same line.
Try it yourself
Write makeMultiplier(factor) that returns a function multiplying its input by factor. Use it to make double and triple.
Show solution
const makeMultiplier = (factor) => (x) => x * factor;
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(5), triple(5)); // 10 15