Lesson 4 of 18 · 0 of 2 exercises solved
Functions & Arrow Functions
You will learn the different ways to write , including , which are the most common in modern code. Functions let you name a piece of work and reuse it.
// Function declaration — hoisted (can be called before it's defined)
function add(a, b) {
return a + b;
}
// Function expression — not hoisted
const multiply = function(a, b) {
return a * b;
};
// Arrow function — modern, concise
const subtract = (a, b) => a - b; // implicit return
const square = x => x * x; // single param, no parens needed
const greet = () => "Hello!"; // no params
// Multi-line arrow function needs explicit return
const divide = (a, b) => {
if (b === 0) throw new Error("Division by zero");
return a / b;
};
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
console.log(square(7)); // 49
// Default parameters
function greetUser(name = "World") {
return `Hello, ${name}!`;
}
console.log(greetUser()); // Hello, World!
console.log(greetUser("Alice")); // Hello, Alice!
// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15JavaScript functions are first- values — you can assign them to , pass them as , and return them from other functions. This enables powerful patterns like and higher-order functions.
// Closures — functions that remember their surrounding scope
function makeCounter(start = 0) {
let count = start;
return {
increment: () => ++count,
decrement: () => --count,
value: () => count,
};
}
const counter = makeCounter(10);
counter.increment();
counter.increment();
console.log(counter.value()); // 12
// Destructuring in function parameters
function displayUser({ name, age, city = "Unknown" }) {
console.log(`${name}, ${age}, ${city}`);
}
displayUser({ name: "Alice", age: 30, city: "Paris" });
// Spread operator
function addThree(a, b, c) {
return a + b + c;
}
const args = [1, 2, 3];
console.log(addThree(...args)); // 6Common question
Is an arrow function just a shorter way to write function?
JavaScript has function declarations, function expressions and arrow functions. All of them create callable values, and "values" is the key word: a function can be passed to another function, which is how map, filter, setTimeout and addEventListener work. Arrow functions add a compact syntax and borrow this from their surroundings, which makes them the natural choice for callbacks.
Use declarations or syntax for functions that need their own this or a hoisted name; use arrows for anything passed inline. Give parameters defaults, collect extras with , and remember that a function without return gives back .
Source: The ECMAScript specification gives arrow functions a "lexical this", a deliberate difference from ordinary functions rather than an abbreviation of them.
Common mix-ups
Each of these sounds reasonable. Think about why it is wrong, then open the explanation.
Arrow functions are just shorthand; the two forms are interchangeable.
A function has to be declared before the line that calls it.
Functions can't be stored in variables or passed around like numbers.
Practice
Write double as an arrow function, and applyTwice(fn, x) as a regular function that applies fn to x two times. applyTwice(double, 3) should be 12.
Functions as values
// const double = ...
// function applyTwice(fn, x) { ... }
console.log(applyTwice(double, 3))
Press Run to try your code, then Check answer to grade it.Give greet a default greeting of "Hello" and make it return a like Hello, Ada! Then call it once with the default and once with "Good evening".
Default parameters
function greet(name, greeting) {
return greeting + ', ' + name
}
console.log(greet('Ada'))
console.log(greet('Ada', 'Good evening'))
Press Run to try your code, then Check answer to grade it.Check yourself
What does a function return if it has no return statement?
Tip: use the ← and → keys to move between lessons.