Functions are the main unit of reuse and abstraction in JavaScript.
A function declaration names a reusable block of code:
function area(width, height = width) {
return width * height;
}Parameters are local variables. JavaScript doesn't check argument counts: missing arguments are undefined, extra ones are ignored. Default parameters (height = width) kick in when the argument is missing or explicitly undefined — not when it's null. A function without a return statement (or with a bare return;) returns undefined.
To accept any number of arguments, use a rest parameter: function sum(...nums) gives you a real array.
Functions are first-class values: you can store them in variables, put them in objects, pass them to other functions and return them from functions. A function expression creates one inline:
const square = function (n) { return n * n; };Passing a function to another function — a callback — is everywhere in JavaScript: button.addEventListener("click", handleClick), items.map(format). Note the missing parentheses: handleClick passes the function; handleClick() would call it immediately and pass its result.
Function declarations are hoisted: you can call them before the line where they are written. Function expressions assigned to const are not usable before that line.
Good functions are small, do one thing, and are named with a verb that says what they do: formatPrice, isValidEmail, loadUser. Prefer returning values over modifying outer variables; it makes functions easier to test and reuse.
Example
function greet(name = "stranger", punctuation = "!") {
return `Hello, ${name}${punctuation}`;
}
console.log(greet("Ada")); // Hello, Ada!
console.log(greet()); // Hello, stranger!
console.log(greet(undefined, "?")); // Hello, stranger?
console.log(greet(null)); // Hello, null! (null is not "missing")
function sum(...nums) {
let total = 0;
for (const n of nums) total += n;
return total;
}
console.log(sum(1, 2, 3)); // 6
// functions are values
function twice(fn, x) { return fn(fn(x)); }
const addTen = function (n) { return n + 10; };
console.log(twice(addTen, 1)); // 21Remember
- Missing arguments are
undefined; defaults apply only toundefined - No
returnmeans the function returnsundefined - Functions are values: pass
fn, notfn(), when giving a callback
Watch out for
- Writing
addEventListener("click", handle()), which callshandleright away and registers its return value.