Sub topic 1
Functions Are Values
Closures depend on one feature of JavaScript: a function is a value. You can store it in a variable, pass it to another function, return it from a function, and put it in an array or object. This chapter covers those operations so the later chapters on scope and closures make sense.
Prerequisites
This chapter assumes you already know:
- Basic JavaScript syntax
- How to declare and call functions
- How
var,let, andconstdeclare variables - How arrays and objects work
- How to pass a callback to a function such as
Array.prototype.map
What "First-Class" Means
A language has first-class functions when functions get the same treatment as any other value. In JavaScript, a function is an object with type "function". A function name is just a variable that holds a reference to that object.
function greet(name) {
return `Hello, ${name}`;
}
const sayHello = greet; // store the function in another variable
console.log(typeof greet); // 'function'
console.log(sayHello('Ada')); // 'Hello, Ada'
console.log(sayHello === greet); // true, same function objectsayHello = greet does not copy or call the function. Both names refer to one object.
The Four Things You Can Do with a Function Value
| Operation | Example | Common use |
|---|---|---|
| Assign to a variable | `const f = function () {}` | Function expressions, arrow functions |
| Pass as an argument | `arr.map(fn)` | Callbacks, event handlers |
| Return from a function | `return () => {}` | Factories, closures |
| Store in a data structure | `{ run: fn }` | Methods, lookup tables |
The example below uses all four:
const operations = {
add: (a, b) => a + b,
sub: (a, b) => a - b
};
function apply(op, a, b) {
return op(a, b);
}
function pick(name) {
return operations[name];
}
console.log(apply(operations.add, 2, 3)); // 5
console.log(pick('sub')(10, 4)); // 6A function that takes a function as an argument or returns one is called a higher-order function. In the example, apply and pick are both higher-order functions.
Returning a Function
Returning a function is the case that leads straight to closures. The outer function finishes running, but the function it returned is still usable:
function makeGreeter() {
return function (name) {
return `Hi, ${name}`;
};
}
const hi = makeGreeter();
console.log(hi('Grace')); // 'Hi, Grace'This returned function uses nothing from makeGreeter. Later chapters show what happens when it does use one of makeGreeter's local variables. That situation is where closures begin.
Common Errors
- Calling when you meant to pass.
button.addEventListener('click', handle())runshandleimmediately and passes its return value. Passhandlewithout parentheses. - Forgetting to call a returned function.
makeGreeter('x')gives you a function, not a string. You needmakeGreeter()('x'). - Expecting a copy. Assigning a function to a new variable creates a second reference to the same function object, not a new function.
Exercise
Given function twice(fn) { return (x) => fn(fn(x)); } and const inc = (n) => n + 1;, what does twice(inc)(5) return, and which of the four operations does twice use?
Show answer
It returns 7. twice receives a function as an argument (fn) and returns a new function, so it is a higher-order function that uses both "pass as an argument" and "return from a function".
Exercise
Why does setTimeout(log(), 1000) not wait one second before logging?
Show answer
log() runs immediately and its return value (usually undefined) goes to setTimeout. Pass the function itself: setTimeout(log, 1000).