Sub topic 2
Functions as Values
This chapter assumes you know core JavaScript syntax, arrow functions, and basic scope, and that you can run code in Node.js or a browser console.
In JavaScript, functions are first-class values. Anything you can do with a number or an object, you can also do with a function. You can store it in a variable, put it in an array or object, pass it to another function, and return it from a function. Every functional technique in this tutorial depends on this.
The four things you can do with a function value
// 1. Assign to a variable
const shout = (s) => s.toUpperCase();
// 2. Store in a data structure
const ops = {
add: (a, b) => a + b,
sub: (a, b) => a - b
};
const steps = [(s) => s.trim(), shout];
// 3. Pass as an argument
function apply(fn, value) {
return fn(value);
}
// 4. Return from a function
function makeGreeter(greeting) {
return (name) => `${greeting}, ${name}`;
}
console.log(ops.add(2, 3)); // 5
console.log(ops['sub'](9, 4)); // 5
console.log(apply(shout, 'hi')); // HI
console.log(steps[1](steps[0](' ok '))); // OK
const hello = makeGreeter('Hello');
console.log(hello('Ada')); // Hello, AdaThe ops object is a dispatch table. You select behavior by key instead of writing a switch statement. Functions that take or return other functions are called higher-order functions, and they get their own chapter. The returned greeter still remembers greeting, which is a closure, also covered in its own chapter.
Referencing versus calling
The name shout refers to the function value. The expression shout('hi') calls it and gives you its result. The parentheses make all the difference.
| Expression | What you get |
|---|---|
| `shout` | The function itself |
| `shout('hi')` | The string `'HI'` |
| `() => shout('hi')` | A new function that calls `shout` later |
Common errors
Calling when you meant to pass
const log = () => console.log('tick');
// Wrong: runs log now and passes its return value (undefined)
// setTimeout(log(), 100);
// Right: pass the function itself
setTimeout(log, 100);Losing `this` when passing a method
When you detach a method from its object, its this binding is lost. Bind the method, or wrap it in an arrow function.
const counter = {
count: 0,
inc() {
this.count += 1;
return this.count;
}
};
const unbound = counter.inc; // `this` no longer points to counter
const bound = counter.inc.bind(counter);
const wrapped = () => counter.inc();
console.log(bound()); // 1
console.log(wrapped()); // 2Passing a function that takes extra arguments
A callback receives every argument the caller supplies. map passes (element, index, array), and parseInt treats the second argument as a radix.
console.log(['1', '2', '3'].map(parseInt)); // [ 1, NaN, NaN ]
console.log(['1', '2', '3'].map((s) => parseInt(s, 10))); // [ 1, 2, 3 ]
console.log(['1', '2', '3'].map(Number)); // [ 1, 2, 3 ]Declarations, expressions, and arrows
All three forms produce function values. A function declaration (function f() {}) is hoisted, so you can call it before the line where it appears. A function expression or arrow function assigned with const can't be used before that line runs. Arrow functions also don't get their own this, which suits small callbacks but makes them a poor choice for object methods that rely on this.
Exercise
Given const tools = { double: (n) => n * 2, negate: (n) => -n };, write a function runAll(fns, value) that takes an array of functions and returns an array of each function's result for value. Then call it with Object.values(tools) and 5.
Show answer
const runAll = (fns, value) => fns.map((fn) => fn(value)); and runAll(Object.values(tools), 5) returns [10, -5]. The functions are treated as ordinary array elements, and each is called with value.
Exercise
Why does button.addEventListener('click', handleClick()) usually fail to respond to clicks?
Show answer
handleClick() runs immediately and passes its return value, usually undefined, as the listener. Pass handleClick without parentheses so the browser can call it when the click happens.