Functions
Declarations, arrow functions, parameters, and return values.
- Define functions as declarations and as arrow functions
- Use parameters, defaults, and return values
- Pass functions as values
Functions are the unit of reuse (the decomposition fundamentals lesson). JavaScript has two main ways to write them, and you'll read both constantly.
Two ways to write a function
A declaration uses the function keyword; an arrow function is a shorter
form assigned to a variable:
function add(a, b) {
return a + b;
}
const addArrow = (a, b) => {
return a + b;
};
// for a single expression, an arrow can be even shorter — the result is returned:
const addShort = (a, b) => a + b;All three compute the same thing. Arrow functions are popular for short callbacks;
declarations read well for named, standalone logic. (They differ in subtle ways
around this, which matters later with classes — for now, treat them as two
spellings.) When a function captures variables from its surrounding scope it forms a closure.
Parameters, defaults, return
Parameters can have defaults, and return hands a value back:
function greet(name, greeting = "Hello") {
return greeting + ", " + name + "!";
}
greet("Ada"); // "Hello, Ada!"
greet("Ada", "Hi"); // "Hi, Ada!"A function with no return (or a bare return) gives back undefined.
Functions are values
As you saw with binding, functions are ordinary values — you can store them and
pass them to other functions. This is what makes array methods like map work:
const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2); // [2, 4, 6]map takes a function and calls it on each element — passing behaviour as data.
Where to go next
Next: control flow — conditionals and loops to drive your functions.