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. Programmers describe this by saying JavaScript has first-class functions.
This chapter covers that idea before the tutorial looks at the different ways to write functions. Declarations, expressions, and arrow functions are three syntaxes that all produce the same kind of thing: a callable object. The later chapters explain how those syntaxes differ in hoisting, this, arguments, and new. Those differences make more sense once you treat every function as a value that can move around your program.
Prerequisites
This chapter assumes you already know:
- Basic JavaScript syntax and how to run a script in Node.js or a browser console
- Variables declared with
var,let, andconst - Objects, properties, and object methods
- Calling a function and passing arguments
- Callbacks at a basic level, such as passing a function to
setTimeoutorArray.prototype.map
All code in this chapter runs as shown in Node.js 18 or later.
What "First-Class" Means
A language feature is first-class when the language lets you use it anywhere a value can go. In JavaScript, a function can be:
- Assigned to a variable or property
- Passed as an argument to another function
- Returned from a function
- Stored in arrays, objects,
Maps, andSets - Given its own properties, because it is an object
The important distinction is between a function reference and a function call. Writing double refers to the function. Writing double(4) runs it and gives you its return value. Most bugs related to first-class functions come from mixing up these two.
Functions Are Objects
Every function is a special kind of object: one that can be called. The typeof operator reports "function" for it, but it still inherits from Object and can carry properties.
function double(n) {
return n * 2;
}
const twice = double;
console.log(twice(4)); // 8
console.log(twice === double); // true
console.log(typeof double); // "function"
console.log(double instanceof Object); // true
console.log(double.name); // "double"
console.log(double.length); // 1
console.log(twice.name); // "double"Some points from this example:
const twice = doublecopies the reference, not the function. There is still only one function, and both names point at it, sotwice === doubleistrue.nameis a built-in property holding the function's name. Assigning the function totwicedoes not rename it.lengthis the number of declared parameters. The parameters chapter shows that default and rest parameters change this count.
Because functions are objects, you can attach your own data to them. This pattern is uncommon in modern code, but it shows the model clearly:
function track() {
track.calls += 1;
return track.calls;
}
track.calls = 0;
track();
track();
console.log(track.calls); // 2Passing Functions as Arguments
A function that takes another function as an argument, or returns one, is called a higher-order function. The array methods map, filter, reduce, forEach, find, and sort are all higher-order functions.
const numbers = [1, 2, 3, 4, 5];
function isEven(n) {
return n % 2 === 0;
}
function square(n) {
return n * n;
}
console.log(numbers.filter(isEven)); // [ 2, 4 ]
console.log(numbers.map(square)); // [ 1, 4, 9, 16, 25 ]
console.log(numbers.filter(isEven).map(square)); // [ 4, 16 ]You pass isEven and do not call it. filter calls it once for each element and keeps the elements where it returns a truthy value.
You can write your own higher-order functions the same way:
function repeat(times, action) {
for (let i = 0; i < times; i++) {
action(i);
}
}
function logIndex(i) {
console.log(`step ${i}`);
}
repeat(3, logIndex);
// step 0
// step 1
// step 2repeat does not know or care what action does. It only relies on action being callable. Code like this separates "when and how often something runs" from "what runs."
Common Error: Calling Instead of Passing
If you add parentheses where you meant to pass a function, you pass its return value instead.
function logClick() {
return 'clicked';
}
const handlers = [];
handlers.push(logClick); // the function itself
handlers.push(logClick()); // the string 'clicked'
console.log(typeof handlers[0]); // "function"
console.log(typeof handlers[1]); // "string"With event listeners and timers, this bug shows up as code that runs right away instead of later, or as a TypeError saying the callback is not a function. If you need to pass arguments, wrap the call in another function. The arrow function chapter covers the short syntax for that.
Common Error: The Callback Gets More Arguments Than You Expect
A higher-order function decides which arguments your callback receives. map passes three: the element, its index, and the whole array. A function that accepts optional extra parameters may misread them.
console.log(['1', '2', '3'].map(parseInt)); // [ 1, NaN, NaN ]
console.log(['1', '2', '3'].map(Number)); // [ 1, 2, 3 ]parseInt takes a second parameter, the radix. map passes the index as that argument, so the calls become parseInt('1', 0), parseInt('2', 1), and parseInt('3', 2). Radix 0 falls back to base 10. Radix 1 is invalid, and '3' is not a valid base-2 digit, so both of those return NaN. When you pass a function you did not write, check its full parameter list.
Returning Functions
A function can build and return a new function. The returned function remembers the variables that were in scope where it was created. This is called a closure.
function makeMultiplier(factor) {
return function (n) {
return n * factor;
};
}
const triple = makeMultiplier(3);
const tenfold = makeMultiplier(10);
console.log(triple(5)); // 15
console.log(tenfold(5)); // 50
console.log(triple === tenfold); // falseEach call to makeMultiplier creates a separate function object with its own factor. That is why triple and tenfold are not equal even though the same code produced them.
Storing Functions in Data Structures
Functions placed in an object or Map can replace long if/switch chains. This is often called a dispatch table.
function add(a, b) {
return a + b;
}
function sub(a, b) {
return a - b;
}
function mul(a, b) {
return a * b;
}
const operations = { '+': add, '-': sub, '*': mul };
function calculate(a, op, b) {
const fn = operations[op];
if (typeof fn !== 'function') {
throw new Error(`Unknown operator: ${op}`);
}
return fn(a, b);
}
console.log(calculate(6, '+', 2)); // 8
console.log(calculate(6, '*', 2)); // 12
try {
calculate(6, '/', 2);
} catch (e) {
console.log(e.message); // Unknown operator: /
}The typeof fn !== 'function' check matters when the lookup key comes from user input. Without the check, a missing key gives undefined, and calling it throws a less helpful TypeError: fn is not a function.
Functions Compare by Reference
Like other objects, functions are equal only when they are the same object. Matching source code does not make them equal.
const a = function (x) {
return x;
};
const b = function (x) {
return x;
};
const c = a;
console.log(a === b); // false
console.log(a === c); // trueThis has practical effects:
| Situation | What goes wrong | Fix |
|---|---|---|
| `removeEventListener` with a freshly written function | The new function is a different object, so nothing is removed | Store the listener in a variable and pass that same reference both times |
| Creating a callback inside a loop or a render function | A new function object is created on every pass | Define it once outside, if identity matters |
| Using a function as a `Map` or `Set` key | Lookups only match the exact same reference | Keep the original reference |
const seen = new Set();
function handler() {}
seen.add(handler);
console.log(seen.has(handler)); // true
console.log(seen.has(function () {})); // falseA Preview: Moving a Method Moves Only the Function
A method is just a property whose value is a function. When you take the method off its object, for example const fn = user.getName, you copy the function reference and nothing else. The link to user is gone. If the function uses this, calling fn() on its own will not see user.
This happens often when you pass methods as callbacks. Regular functions and arrow functions handle it differently, and that difference explains much of why arrow functions exist. The chapters on this binding and on methods, callbacks, and class fields cover it in detail.
Summary
- Functions in JavaScript are callable objects.
typeofreports"function", and they can have properties such asnameandlength. - Assigning a function copies a reference. Function equality checks identity, so two identical-looking functions are not equal.
- Higher-order functions accept or return functions. Passing
fnhands over the function, while passingfn()hands over its result. - Returned functions close over the variables where they were created.
- Every syntax in the following chapters produces this same kind of value. The syntaxes differ in hoisting,
this,arguments, and whethernewworks.
Exercise
What does this code print, and why? function greet() { return 'hi'; } const items = [greet, greet(), greet.name, greet.length]; console.log(items.map(x => typeof x));
Show answer
It prints [ 'function', 'string', 'string', 'number' ]. greet is the function reference. greet() is its return value, the string 'hi'. greet.name is the string 'greet'. greet.length is 0, the number of declared parameters, so its type is 'number'.
Exercise
A developer writes button.addEventListener('click', function () { save(); }) and later button.removeEventListener('click', function () { save(); }). The listener keeps firing. Explain the cause and give a fix.
Show answer
Each function () { save(); } creates a new function object. Functions compare by reference, so removeEventListener gets a different object from the one that was registered and removes nothing. The fix is to store the function once, for example const onClick = function () { save(); };, and pass onClick to both addEventListener and removeEventListener.
Exercise
Write a function compose(f, g) that returns a new function which, given x, returns f(g(x)). Using it with const inc = n => n + 1 and const dbl = n => n * 2, what is compose(inc, dbl)(5)?
Show answer
function compose(f, g) { return function (x) { return f(g(x)); }; } The call compose(inc, dbl)(5) first computes dbl(5) = 10, then inc(10) = 11, so the result is 11.