Functions
A function is a named, reusable block of code. You write the steps once and then call the function whenever you need them, passing in different values each time. Functions keep programs short, organised and easy to test, and in JavaScript they are also values you can pass around.
Declaring and calling a function
A function declaration starts with the keyword function, then a name, a list of parameters in round brackets and a body in curly braces. Writing the name followed by brackets calls (runs) it.
function greet(name) {
return `Karibu, ${name}!`;
}
console.log(greet("Achieng"));
console.log(greet("Musa"));
Here name is a parameter, a placeholder variable that exists inside the function. "Achieng" and "Musa" are arguments, the actual values passed in each call. Function names follow the same camelCase rules as variables and are usually verbs: calculateTotal, showMenu, isValidPhone.
Returning a value
The return statement sends a value back to the place where the function was called, and ends the function immediately. The call itself then becomes that value, so you can store it, print it or use it in a calculation.
function totalCost(price, qty) {
return price * qty;
}
const bill = totalCost(50, 4);
console.log(bill);
console.log(totalCost(30, 2) + totalCost(10, 5));
return jumps back, carrying the result, which replaces the call.A function without a return (or with a bare return;) gives back undefined:
function logArea(width, height) {
console.log("Area:", width * height);
}
const result = logArea(3, 4);
console.log(result);
Printing is not returning. logArea shows 12 on screen, but the value is lost; result is undefined. If other code needs the answer, return it. Also, any code after a return in the same block never runs.
Parameters: missing, default and rest
JavaScript doesn't check how many arguments you pass. A missing argument simply becomes undefined, which can produce odd results:
function describe(name, county) {
return name + " lives in " + county;
}
console.log(describe("Otieno"));
Give a parameter a default value with =; it is used when the argument is missing or undefined. A rest parameter written with three dots collects any number of arguments into an array:
function totalCost(price, qty = 1) {
return price * qty;
}
console.log(totalCost(50, 4));
console.log(totalCost(50));
function sum(...numbers) {
let total = 0;
for (const n of numbers) {
total += n;
}
return total;
}
console.log(sum(1, 2, 3));
console.log(sum(10, 20, 30, 40));
A rest parameter must be the last one in the list.
Function expressions and hoisting
A function can also be created as an expression and stored in a variable:
console.log(square(4));
function square(n) {
return n * n;
}
console.log(cube(2));
const cube = function (n) {
return n ** 3;
};
Function declarations are fully hoisted, so you can call square even above the line where it is written. A function expression stored in a const follows the normal variable rules and sits in the temporal dead zone until its line runs (see Variables). Many developers write expressions with the shorter arrow syntax.
Functions are values
In JavaScript a function is a value like a number or string. You can store it in a variable, put it in an object, and pass it to another function. A function passed as an argument is called a callback.
function applyTwice(fn, value) {
return fn(fn(value));
}
function double(n) {
return n * 2;
}
console.log(applyTwice(double, 5));
Note that we pass double without brackets. double is the function itself; double(5) would call it immediately and pass its result, 10. Callbacks are everywhere in JavaScript: event listeners, timers and array methods such as map and filter all take them.
Good functions do one job, have a name that says what that job is, and take their inputs as parameters rather than reading global variables. Such functions are easy to reuse and easy to test in the console.
Key points
- Declare with
function name(params) { }and call withname(args). returnsends a value back and ends the function; without it, the result isundefined.- Missing arguments are
undefined; use defaults (qty = 1) and rest parameters (...numbers). - Declarations are hoisted; function expressions in
constare not usable before their line. - Functions are values and can be passed to other functions as callbacks.
Tip: use the ← and → keys to move between pages.
