Sub topic 1
Functions Are Values
In JavaScript, a function is a value, just like a number, a string, or an object. You can store it in a variable, put it in an array, pass it to another function, and return it from a function. Languages that allow this are said to have first-class functions. The rest of this tutorial depends on this idea, because declarations, expressions, and arrow functions are all different ways of producing the same kind of value.
Prerequisites
This chapter assumes you already know:
- Basic JavaScript syntax
- Variables declared with
var,let, andconst - Objects and object methods
- Calling functions and passing arguments
- Basic callbacks, such as
setTimeoutor array methods likemap
What "first-class" means in practice
A value is first-class when the language puts no special limits on it. Functions in JavaScript can do anything other values can do:
| Operation | Example |
|---|---|
| Assign to a variable | `const f = greet;` |
| Store in a data structure | `const ops = [add, sub];` |
| Pass as an argument | `[1, 2].map(double)` |
| Return from a function | `return () => n + 1;` |
| Have properties | `greet.name`, `greet.length` |
The example below runs every operation in the table.
function double(n) {
return n * 2;
}
// Assign to another variable: both names point to the same function
const twice = double;
console.log(twice(4)); // 8
console.log(twice === double); // true
// Store in an object and an array
const ops = { double, half: n => n / 2 };
const pipeline = [double, ops.half, double];
console.log(ops.half(10)); // 5
// Pass as an argument
console.log([1, 2, 3].map(double)); // [ 2, 4, 6 ]
// Return from a function
function makeAdder(amount) {
return function (n) {
return n + amount;
};
}
const addTen = makeAdder(10);
console.log(addTen(5)); // 15
// Apply a list of functions in order
const result = pipeline.reduce((value, fn) => fn(value), 3);
console.log(result); // 12
// Functions are objects with properties
console.log(typeof double); // "function"
console.log(double.name); // "double"
console.log(double.length); // 1 (number of declared parameters)When you write const twice = double, nothing gets copied. Both names refer to the same function object, the same way two variables can refer to the same array.
Referencing a function versus calling it
Most early bugs with function values come from mixing up fn and fn(). Without parentheses you have the function itself. With parentheses you have whatever the function returns.
function sayHi() {
return 'hi';
}
console.log(typeof sayHi); // "function"
console.log(typeof sayHi()); // "string"
// Common mistake: this calls sayHi immediately and passes "hi" to setTimeout
// setTimeout(sayHi(), 100);
// Correct: pass the function so setTimeout can call it later
setTimeout(sayHi, 100);Higher-order functions
A higher-order function is a function that takes a function as an argument, returns a function, or both. map, filter, reduce, setTimeout, and makeAdder above are all higher-order. Code written this way is often short, because the varying behavior comes in as a parameter rather than through if branches.
function repeat(times, action) {
for (let i = 0; i < times; i++) {
action(i);
}
}
repeat(3, i => console.log(`step ${i}`));
// step 0
// step 1
// step 2Why this matters for the rest of the tutorial
Every form you will meet next produces a function value. Where they differ is in when the value becomes available (hoisting), what name it carries, and how it treats this, arguments, and new. Keep the value model in mind and those differences become easier to reason about.
Exercise
Given const log = console.log; const fns = [Math.max, log];, what does fns[0](3, 9, 4) return, and what is typeof fns[1]?
Show answer
fns[0] is the same function as Math.max, so fns[0](3, 9, 4) returns 9. fns[1] is a reference to console.log, so typeof fns[1] is "function".
Exercise
Write makeMultiplier(factor) so that it returns a function, and makeMultiplier(3)(7) returns 21.
Show answer
function makeMultiplier(factor) { return n => n * factor; }. Calling makeMultiplier(3) returns a function that remembers factor as 3. Calling that function with 7 returns 21.