Sub topic 1
Functions Are Values
In JavaScript, a function is a value, like a number, a string, or an object. You can store a function in a variable, put it in an array, attach it to an object, pass it to another function, and return it from a function. Languages that allow all of this are said to have first-class functions. Callbacks depend on this feature, so this chapter covers it before the rest of the tutorial uses it.
Prerequisites
This chapter assumes you already know:
- How to declare variables and functions in JavaScript, including arrow functions
- How arrays and objects work
- How to run a script in Node.js or the browser console
- How
let,const, andvardiffer in scope
A Function Name Holds a Reference
When you declare a function, JavaScript creates a function object and binds a name to it. Using the name without parentheses gives you a reference to that object. Adding parentheses calls the function and gives you its return value.
function greet(name) {
return `Hello, ${name}`;
}
const sayHello = greet; // no parentheses: copy the reference
console.log(sayHello('Ada')); // Hello, Ada
console.log(sayHello === greet); // true: both names point to one object
console.log(typeof greet); // function
console.log(greet.name); // greet
console.log(greet.length); // 1 (number of declared parameters)The assignment const sayHello = greet does not copy the function's code. It copies a reference, so sayHello and greet point to the same object. Functions are objects, so they have properties such as name and length.
Storing Functions in Data Structures
A function reference can go anywhere a value can go. Objects of functions are a common way to build lookup tables, also called dispatch tables, which replace long if/else chains.
const ops = {
add: (a, b) => a + b,
sub: (a, b) => a - b,
mul: (a, b) => a * b,
};
function calculate(opName, a, b) {
const op = ops[opName];
if (typeof op !== 'function') {
throw new Error(`Unknown operation: ${opName}`);
}
return op(a, b);
}
console.log(calculate('add', 2, 3)); // 5
console.log(calculate('mul', 4, 5)); // 20
const steps = [Math.abs, Math.sqrt];
console.log(steps[1](steps[0](-16))); // 4Passing and Returning Functions
A function that takes a function as an argument, or returns one, is called a higher-order function. The example below does both.
function applyTwice(fn, value) {
return fn(fn(value));
}
function makeMultiplier(factor) {
return (x) => x * factor;
}
const triple = makeMultiplier(3);
console.log(triple(4)); // 12
console.log(applyTwice(triple, 2)); // 18makeMultiplier returns a new function each time you call it. The returned function still has access to factor after makeMultiplier has returned. That behavior is a closure, which a later chapter covers in the context of callbacks.
applyTwice receives a function and decides when to call it. That is the basic idea of a callback, and the next chapter defines callbacks properly.
The Most Common Mistake: Calling Instead of Passing
The bug people hit most often is adding parentheses where a reference was expected.
function makeMultiplier(factor) {
return (x) => x * factor;
}
function applyTwice(fn, value) {
return fn(fn(value));
}
const triple = makeMultiplier(3);
try {
applyTwice(triple(), 2); // triple() runs now and returns NaN
} catch (err) {
console.log(err.message); // fn is not a function
}triple() runs right away with x set to undefined, so it returns NaN. That NaN, not the function, is what applyTwice receives.
| Expression | What it evaluates to |
|---|---|
| `greet` | The function object |
| `greet('Ada')` | The return value, `'Hello, Ada'` |
| `() => greet('Ada')` | A new function that calls `greet` when it runs |
| `makeMultiplier(3)` | A new function returned by `makeMultiplier` |
Declarations and Expressions
Function declarations are hoisted, so you can call one before the line that defines it. A function expression assigned to const or let cannot be used before its line runs, because accessing the variable earlier throws a ReferenceError. Both kinds produce the same type of value, and both can be passed around in the same way.
Exercise
Given const f = makeMultiplier(2);, what does applyTwice(makeMultiplier, 5) return, and why?
Show answer
It returns a function. The first call, makeMultiplier(5), returns a function. The second call passes that function in as factor, so the result is another arrow function, (x) => x * factor, where factor is a function. Calling that result with a number gives NaN, because multiplying a number by a function produces NaN.
Exercise
Write a function compose(f, g) that returns a new function computing f(g(x)). Use it with Math.sqrt and Math.abs to compute the square root of the absolute value of -9.
Show answer
const compose = (f, g) => (x) => f(g(x)); const sqrtAbs = compose(Math.sqrt, Math.abs); console.log(sqrtAbs(-9)); // 3