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, pass it to another function, return it from a function, and keep it in an array or object. Closures depend on this. A closure is something a function carries with it after it leaves the place where it was created. If functions could not be passed around and returned, there would be nothing for them to carry.
This chapter sets up the vocabulary and habits the rest of the tutorial uses. It does not cover scope or closures yet. Those topics start in the next chapter.
Prerequisites
This chapter assumes you are comfortable with:
- Basic JavaScript syntax and running code in Node.js or a browser console
- Declaring and calling functions
- Declaring variables with
var,let, andconst - Working with arrays and objects
- Passing a function as a callback, for example to
Array.prototype.maporsetTimeout
You do not need to know anything about scope rules yet.
What "First-Class" Means
A language has first-class functions when functions can be used everywhere other values can. In JavaScript you can do four things with any function:
- Assign it to a variable or property.
- Pass it as an argument to another function.
- Return it from another function.
- Store it inside a data structure.
A function that takes a function as an argument, or returns one, is called a higher-order function. map, filter, setTimeout, and addEventListener are all higher-order functions you have probably used already.
Assigning a function to a variable
function greet(name) {
return `Hello, ${name}`;
}
const sayHello = greet;
console.log(sayHello('Ada')); // Hello, Ada
console.log(sayHello === greet); // trueThe line const sayHello = greet does not copy the function or call it. It makes sayHello refer to the same function object that greet refers to. That is why the strict equality check returns true.
Passing a function as an argument
function applyTwice(fn, value) {
return fn(fn(value));
}
const addThree = (n) => n + 3;
const shout = (s) => s.toUpperCase() + '!';
console.log(applyTwice(addThree, 10)); // 16
console.log(applyTwice(shout, 'hi')); // HI!!applyTwice does not know or care what fn does. It only needs fn to be callable. This kind of separation is the reason higher-order functions are useful: the calling code decides the behavior, and the higher-order function decides when and how often to run it.
Returning a function
function pickOperation(symbol) {
if (symbol === '+') return (a, b) => a + b;
if (symbol === '*') return (a, b) => a * b;
throw new Error(`Unknown operation: ${symbol}`);
}
const add = pickOperation('+');
console.log(add(2, 3)); // 5
console.log(pickOperation('*')(4, 5)); // 20pickOperation('*')(4, 5) contains two calls in a row. The first call returns a function, and the second call runs that function right away.
The returned functions here use only their own parameters a and b. Later chapters ask what happens when a returned function uses a variable that belongs to the function that created it, after that outer function has already finished running. The answer to that question is a closure.
Storing functions in data structures
const operations = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b
};
console.log(operations.subtract(10, 4)); // 6
const steps = [
(s) => s.trim(),
(s) => s.toLowerCase(),
(s) => s.replace(/\s+/g, '-')
];
const slug = steps.reduce((value, step) => step(value), ' Hello World Again ');
console.log(slug); // hello-world-againA lookup object of functions can replace a long switch statement. An array of functions works as a small pipeline. Both patterns only work because functions are ordinary values.
Functions Are Objects
A function is a special kind of object that can be called. It has properties, and you can add your own.
function area(width, height) {
return width * height;
}
console.log(typeof area); // function
console.log(area.name); // area
console.log(area.length); // 2 (number of declared parameters)
area.description = 'Computes the area of a rectangle';
console.log(area.description); // Computes the area of a rectangle
console.log(area instanceof Object); // truetypeof returns 'function' for functions, but they still inherit from Object. The length property counts declared parameters, but it stops at the first parameter that has a default value or is a rest parameter. For example, ((a, b = 1, ...rest) => {}).length is 1.
Three Ways to Create a Function
All three forms below produce function values. They differ in hoisting, in this binding, and in whether they can be used with new.
// Function declaration
function double(n) {
return n * 2;
}
// Function expression (here, a named one)
const triple = function tripleFn(n) {
return n * 3;
};
// Arrow function
const square = (n) => n * n;
console.log(double(4), triple(4), square(4)); // 8 12 16
console.log(triple.name); // tripleFn| Form | Hoisted as callable? | Own `this`? | Usable with `new`? | Typical use |
|---|---|---|---|---|
| Function declaration | Yes, the whole function | Yes | Yes | Top-level named helpers |
| Function expression | No, follows `const`/`let`/`var` rules | Yes | Yes | Values assigned conditionally or passed inline |
| Arrow function | No, follows `const`/`let`/`var` rules | No, uses the surrounding `this` | No | Short callbacks and returned functions |
The this column matters later. Chapter "Closures, this, and Arrow Functions" explains why an arrow function's lack of its own this makes it behave like a closure over this.
Hoisting differences in practice
console.log(early(2)); // 4, declarations are callable before they appear
function early(n) {
return n * 2;
}
try {
late(2);
} catch (err) {
console.log(err.name); // ReferenceError
}
const late = (n) => n * 2;The function declaration is fully available at the top of its scope. The arrow function is stored in a const, and a const cannot be read before its declaration line runs. The chapter on block and function scope explains the rule behind this.
Common Errors
Calling a function when you meant to pass it
The most frequent mistake with function values is adding parentheses where they don't belong.
const double = (n) => n * 2;
const numbers = [1, 2, 3];
console.log(numbers.map(double)); // [ 2, 4, 6 ]
try {
numbers.map(double()); // double() runs now and returns NaN
} catch (err) {
console.log(err.message); // NaN is not a function
}double is the function. double() is the result of calling it. map needs the function, so you pass double without parentheses. The same applies to setTimeout(done, 1000) versus the wrong setTimeout(done(), 1000), which runs done immediately and hands setTimeout its return value.
When you need to pass arguments, wrap the call in a new function:
function log(message) {
console.log(message);
}
setTimeout(() => log('one second later'), 1000);The arrow function is the value that setTimeout stores, and log('one second later') only runs when the timer fires.
Losing `this` when extracting a method
const user = {
name: 'Grace',
hello() {
return `Hi, ${this && this.name}`;
}
};
const detached = user.hello;
console.log(user.hello()); // Hi, Grace
console.log(detached()); // Hi, undefined (or an error in strict mode code that reads this.name directly)Assigning a method to a variable copies the reference to the function. It does not keep the object that the method came from. The value of this depends on how a function is called, not on where it is stored. The fixes, bind or an arrow wrapper such as () => user.hello(), come up again later in the tutorial.
Why This Matters for Closures
Every closure pattern in this tutorial follows the same shape: a function creates another function and either returns it or hands it to someone else, such as a timer, an event system, or a caller. The inner function then runs later, somewhere else. You have now seen each piece of that shape on its own. The next chapters explain the missing part: which variables the inner function can still see when it finally runs.
Exercise
What does this code print, and why? const f = (x) => x + 1; const g = f; f.tag = 'inc'; console.log(g.tag, g === f, g(1));
Show answer
It prints inc true 2. g refers to the same function object as f, so a property added through f is visible through g, the two references are strictly equal, and calling g(1) runs the same code and returns 2.
Exercise
A teammate writes button.addEventListener('click', handleClick(item.id)); and the handler runs once on page load and never on click. Explain the bug and give a fix.
Show answer
handleClick(item.id) is called immediately while the listener is being registered, and its return value (probably undefined) is passed to addEventListener instead of a function. Pass a function instead: button.addEventListener('click', () => handleClick(item.id));.
Exercise
Write a function compose(f, g) that returns a new function which, given x, returns f(g(x)). Use it to build incThenDouble from (n) => n * 2 and (n) => n + 1, and state what incThenDouble(3) returns.
Show answer
const compose = (f, g) => (x) => f(g(x)); const incThenDouble = compose((n) => n * 2, (n) => n + 1); Calling incThenDouble(3) adds 1 first to get 4, then doubles it, returning 8.