β‘
EPISODE 03
declaration Β· arrow Β· default params Β· rest/spread
Functions
Master the three function forms (declaration, expression, arrow), default and rest parameters, and the spread operator.
functionarrowdefaultrestspread
Duration
β± About 2 hours
Level
π Beginner+
Prerequisite
π― js-02
OUTCOME
Write reusable, well-typed functions in modern JavaScript
What you'll learn
- 1Choose between function declaration, expression, and arrow
- 2Use default and rest parameters
- 3Apply the spread operator to clone and combine
- 4Understand the basics of closures
1. Three Forms
javascript
// 1. Function declaration (hoisted)
function add(a, b) {
return a + b;
}
// 2. Function expression
const sub = function (a, b) {
return a - b;
};
// 3. Arrow function (modern)
const mul = (a, b) => a * b;
const sq = n => n * n; // single arg, no parens
const noop = () => {}; // no argsArrow functions do not have their own this β handy in callbacks and class methods.
2. Default & Rest Parameters
javascript
function greet(name, greeting = "Hello") {
return `${greeting}, ${name}!`;
}
function sum(...nums) { // rest collects extra args into array
return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 103. Spread Operator
javascript
const a = [1, 2, 3];
const b = [4, 5, 6];
const combined = [...a, ...b]; // [1,2,3,4,5,6]
const copy = [...a]; // shallow copy
const user = { name: "Alice", age: 30 };
const updated = { ...user, age: 31 }; // new object with overridden age4. Closures
javascript
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const counter = makeCounter();
counter(); // 1
counter(); // 2The inner function remembers count from its enclosing scope, even after makeCounter has returned.
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β