JavaScript · Lesson 3 of 6
Functions and Scope
Declarations, arrow functions, closures and how scope works.
- Beginner
- 15 min read
- 3 objectives
Before this lessonLesson 2: Variables and Types
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.
Functions are the building blocks
A function packages a task so you can run it whenever you like, with different inputs each time. Instead of repeating the same lines in five places, you write them once, name them, and call the name. In JavaScript functions are also values: you can store them in variables, pass them to other functions and return them, which is why so much JavaScript code is built from small functions handed to other functions.
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Ada"));
console.log(greet("Linus"));Hello, Ada! Hello, Linus!
Three ways to write one
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.
Default, rest and destructured parameters
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.
Functions as arguments
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
Parameters, arguments and return values
The names in the definition are parameters; the actual values you pass are arguments. A function without a return gives back undefined. A function stops running the moment it returns.
function area(w, h) {
if (w <= 0 || h <= 0) return 0; // early return
return w * h;
}
console.log(area(3, 4), area(-1, 5));
function noReturn() { const x = 1; }
console.log(noReturn());12 0 undefined
Arrow functions in plain words
An arrow function is a shorter way to write a small function. Read (x) => x * 2 as "given x, produce x times 2." When the body is one expression, the return is implied.
const double = (x) => x * 2;
const add = (a, b) => a + b;
const logAndAdd = (a, b) => {
console.log("adding", a, b);
return a + b;
};
console.log(double(21), add(2, 3), logAndAdd(4, 5));adding 4 5 42 5 9
Closures: a function that remembers
A function remembers the variables that existed where it was created, even after that outer code has finished. This lets you build functions that keep private state, like a counter that nobody else can tamper with.
function makeCounter() {
let count = 0;
return () => {
count += 1;
return count;
};
}
const a = makeCounter();
const b = makeCounter();
console.log(a(), a(), a());
console.log(b());1 2 3 1
Callbacks: passing a function to a function
function repeat(times, action) {
for (let i = 1; i <= times; i++) action(i);
}
repeat(3, (n) => console.log("round", n));
[10, 20, 30].forEach((v, i) => console.log(i, v));round 1 round 2 round 3 0 10 1 20 2 30
Key takeaways
- A function names reusable work: parameters in,
returnout. - Arrow functions
(a, b) => a + bare concise; use them for short callbacks. - Closures let a function remember the variables from where it was created.
- Functions are values: store them, pass them, and return them.
// Write your solution here
