Skip to content

Lesson 5 of 50JavaScript basics

Functions and Arrow Functions

Write functions three ways, use default and rest parameters, and pass functions around as values.

13 min read0/6 questions

Functions are the main building block of JavaScript. Every React component is a function, every event handler is a function, and array methods like map take functions as arguments. You will write thousands of them, so it pays to know the three syntaxes and the small differences between them.

Three ways to write a function

The same function, written three ways:

JavaScript
// 1. Function declarationfunction add(a, b) { return a + b;} // 2. Function expression: a function stored in a variableconst subtract = function (a, b) { return a - b;}; // 3. Arrow function (ES2015)const multiply = (a, b) => a * b; console.log(add(2, 3), subtract(2, 3), multiply(2, 3));
Output
Press Run (⌘ Enter) to see what happens.

A declaration starts with the function keyword as a statement. An expression creates a function as a value and assigns it, like any other value. An arrow function is a shorter expression: parameters, =>, then the body.

Arrow functions have a few shorthand rules:

  • With an expression body (no braces), the result is returned automatically: (a, b) => a * b.
  • With braces, you need return: (a, b) => { return a * b; }.
  • One parameter needs no parentheses: n => n * 2. Zero parameters need empty ones: () => 42.
Quick check
What does double(4) return?
const double = (n) => { n * 2 };
Need a nudge? A hint rules out a wrong answer.

Hoisting differs

Function declarations are hoisted completely: you can call them above the line where they are written. Function expressions and arrows follow the rules of the variable that holds them. With const, calling them early throws a ReferenceError.

Predict the outputJavaScript

What does this print?

console.log(greet("Ada"));

function greet(name) {
return "Hi " + name;
}

try {
wave("Sam");
} catch (e) {
console.log(e.name);
}

const wave = (name) => "Bye " + name;
Need a nudge? Hints walk you through it.

Many teams write helpers as declarations at the bottom of a file so the main logic reads top to bottom. Others prefer const arrows everywhere for consistency. Both are fine. The real difference between arrows and regular functions is this, which arrows do not have of their own. That gets a full section in the scope and this lesson; for now, use arrows for short callbacks.

Parameters: defaults and rest

JavaScript does not check how many arguments you pass. Missing ones are undefined, extra ones are ignored. Two features make this safer.

A default parameter is used when the argument is missing or undefined:

JavaScript
function greet(name = "friend", greeting = "Hello") { return `${greeting}, ${name}!`;} console.log(greet());console.log(greet("Leo"));console.log(greet("Leo", "Welcome back"));console.log(greet(undefined, "Hey")); // undefined triggers the defaultconsole.log(greet(null)); // null does not
Output
Press Run (⌘ Enter) to see what happens.

A rest parameter (...name) collects all remaining arguments into a real array. It must be last.

JavaScript
function sum(...nums) { return nums.reduce((total, n) => total + n, 0);} function tag(label, ...values) { return `${label}: ${values.join(", ")}`;} console.log(sum(1, 2, 3, 4));console.log(sum());console.log(tag("primes", 2, 3, 5, 7));
Output
Press Run (⌘ Enter) to see what happens.

Python developers will recognise these as def greet(name="friend") and def total(*nums). Unlike Python, JavaScript default values are evaluated on every call, so function add(item, list = []) gets a fresh array each time. The shared mutable default trap from Python does not exist here.

Quick check
What does greet(null) return?
function greet(name = "friend") {
return "Hi " + name;
}
Need a nudge? A hint rules out a wrong answer.

Returning an object from an arrow

A common stumble: you want an arrow to return an object literal.

JavaScript
const makeUserBroken = (name) => { name: name };const makeUser = (name) => ({ name, active: true }); console.log(makeUserBroken("Ada"));console.log(makeUser("Ada"));
Output
Press Run (⌘ Enter) to see what happens.

In makeUserBroken, the braces are read as a function body, and name: is read as a statement label. The function returns undefined. Wrapping the object in parentheses tells the parser "this is an expression". You will write => ({ ... }) constantly in React reducers and map calls.

(Note { name } inside the second version: that is shorthand for { name: name }, covered in the next lesson.)

Functions are values

In JavaScript, functions are first-class values: you can store them in variables, put them in arrays and objects, pass them as arguments and return them from other functions. Python works the same way.

A function is an object a name points to
const add = (a, b) => a + b;
NamesObjects in memoryaddfunction(a, b) => a + b

Creating a function makes a function object in memory. add is just a name pointing at it.

1/4

A function passed to another function is a callback. The receiving function decides when to call it.

JavaScript
function repeat(times, action) { for (let i = 0; i < times; i++) action(i);} repeat(3, (i) => console.log(`tick ${i}`)); const operations = { add: (a, b) => a + b, max: Math.max,};console.log(operations.add(2, 5), operations.max(2, 5)); const prices = [12, 5, 30];console.log(prices.map((p) => p * 2));console.log(prices.filter((p) => p > 10));
Output
Press Run (⌘ Enter) to see what happens.

A function that takes or returns another function is a higher-order function. repeat, map and filter are all higher-order. Returning a function is just as common:

JavaScript
function multiplier(factor) { return (n) => n * factor;} const double = multiplier(2);const triple = multiplier(3);console.log(double(10), triple(10));
Output
Press Run (⌘ Enter) to see what happens.

multiplier(2) returns a brand new function that remembers factor. That memory is called a closure, and the scope lesson explores it fully.

Predict the outputJavaScript

What does this print?

const apply = (fn, x) => fn(fn(x));
const addTen = (n) => n + 10;
console.log(apply(addTen, 1));
Need a nudge? Hints walk you through it.

Passing vs calling

The most common callback bug is writing fn() where you meant fn. With parentheses you call the function right now and pass its result.

Quick check
You want setTimeout to run save after one second. Which line is correct?
Need a nudge? A hint rules out a wrong answer.
Put it in order3 steps

pipe(f, g, h)(x) should compute h(g(f(x))). Order the steps for pipe(trim, toLower, addBang)(" HI ").

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeEasy

once

Write once(fn). It returns a new function that calls fn the first time it is called (passing along any arguments) and returns its result. Every later call does not call fn again and returns that same first result.

const init = once(() => { console.log("setting up"); return 42; });
init(); // logs "setting up", returns 42
init(); // logs nothing, returns 42

Useful for initialising a connection or registering a handler exactly once. Careful: fn might return undefined or 0, and it must still run only once.

JavaScript
function once(fn) { // Return a new function that remembers whether fn has already run. return fn;}
ChallengeEasy

pipe

Write pipe(...fns). It returns a function that takes one value and passes it through every function left to right, feeding each result into the next.

const slugify = pipe(
  (s) => s.trim(),
  (s) => s.toLowerCase(),
  (s) => s.replaceAll(" ", "-"),
);
slugify("  Hello World "); // "hello-world"

With no functions, pipe() returns a function that gives back its input unchanged.

JavaScript
function pipe(...fns) { // Return a function of one argument that runs each fn in order. return (x) => undefined;}
Key terms
function declaration
function name() {} as a statement. Fully hoisted, so it can be called before its line.
arrow function
(a) => expr. Short syntax, implicit return without braces, and no own this.
default parameter
(x = 5): used when the argument is missing or undefined (not null). Evaluated on each call.
rest parameter
(...args): collects the remaining arguments into a real array. Must be last.
callback
A function passed to another function, which decides when to call it.
higher-order function
A function that takes a function as an argument or returns one, like map or multiplier.