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. This one property is what makes callbacks possible. Every later chapter in this tutorial builds on it.
This chapter covers the working model of functions as values. It also covers the mistakes that come from confusing a function with the result of calling it.
Prerequisites
This chapter assumes you already know:
- How to declare variables with
let,const, andvar, and how their scoping differs. - How to write function declarations and arrow functions.
- How arrays and objects work, including property access with dot and bracket notation.
- How to run a script in Node.js or paste code into a browser console.
You do not need any prior knowledge of asynchronous code. That comes later.
What "first-class" means
A language has first-class functions when its functions can be used anywhere other values can. In JavaScript, a function can:
- Be assigned to a variable or constant.
- Be stored as an element of an array or a property of an object.
- Be passed as an argument to another function.
- Be returned from another function.
- Have properties of its own, because functions are objects.
Many older languages let you define functions but don't let you treat them as data. In those languages, passing behavior around requires workarounds such as function pointers or single-method interfaces. JavaScript makes this direct.
// 1. Assigned to a variable
const greet = function (name) {
return `Hello, ${name}`;
};
// 2. Stored in an array and an object
const operations = [Math.max, Math.min];
const formatter = { shout: (s) => s.toUpperCase() };
// 3. Passed as an argument
function applyTo(value, fn) {
return fn(value);
}
// 4. Returned from a function
function makeAdder(n) {
return (x) => x + n;
}
console.log(greet('Ada')); // Hello, Ada
console.log(operations[0](3, 9)); // 9
console.log(formatter.shout('hi')); // HI
console.log(applyTo('quiet', formatter.shout)); // QUIET
console.log(makeAdder(10)(5)); // 15Each line in the final block uses a function as data first and only then calls it.
A function is an object
typeof reports 'function' for functions. Underneath, a function is a special kind of object that can be called. It inherits from Function.prototype, and you can attach properties to it like any other object.
function area(width, height) {
return width * height;
}
console.log(typeof area); // 'function'
console.log(area instanceof Object); // true
console.log(area.name); // 'area'
console.log(area.length); // 2 (number of declared parameters)
area.unit = 'm²';
console.log(area.unit); // 'm²'Two built-in properties are useful when debugging callbacks:
| Property | What it holds | Notes |
|---|---|---|
| `name` | The function's name | Inferred from the variable for anonymous function expressions and arrows assigned to a `const`/`let` |
| `length` | Count of declared parameters | Stops counting at the first default or rest parameter |
const anon = () => {};
const withDefaults = (a, b = 2, c) => {};
const withRest = (a, ...rest) => {};
console.log(anon.name); // 'anon'
console.log(withDefaults.length); // 1
console.log(withRest.length); // 1
console.log((() => {}).name); // '' (nothing to infer from)The name shows up in stack traces. An inline anonymous callback that throws is harder to trace than a named one. This is one reason later chapters prefer named functions when flattening nested callbacks.
The reference and the call
The most important distinction in this chapter is between fn and fn().
fnis the function itself, a reference to the function object.fn()runs the function now and evaluates to its return value.
function now() {
return Date.now();
}
const ref = now; // the function
const value = now(); // a number, such as 1764000000000
console.log(typeof ref); // 'function'
console.log(typeof value); // 'number'When you hand a function to someone else so they can call it later, you pass the reference. Adding parentheses runs it immediately and passes whatever it returned instead.
function sayDone() {
console.log('done');
}
// Correct: setTimeout receives the function and calls it later
setTimeout(sayDone, 100);
// Wrong: sayDone runs right now, logs 'done', returns undefined,
// and setTimeout receives undefined
// setTimeout(sayDone(), 100);
// In Node.js this throws: TypeError [ERR_INVALID_ARG_TYPE]If you need to pass arguments and still delay the call, wrap the call in a new function:
function greetUser(name) {
console.log(`Hi, ${name}`);
}
setTimeout(() => greetUser('Grace'), 100); // runs later with the argumentThe arrow function is the value being passed. Its body, greetUser('Grace'), runs only when the arrow is called.
Variables hold references, not copies
Assigning a function to a second variable doesn't copy it. Both names point to the same function object.
const greet = (name) => `Hello, ${name}`;
const sayHello = greet;
const obj = { hello: greet };
console.log(sayHello === greet); // true
console.log(obj.hello === greet); // true
console.log(sayHello.name); // 'greet' (the name stays with the object)Equality between functions compares identity. Two functions with identical source code are still different objects:
const a = (x) => x * 2;
const b = (x) => x * 2;
console.log(a === b); // false
console.log(a === a); // trueThis matters in practice. APIs that remove a previously registered callback find it by identity. If you register an inline arrow, you have no reference left to remove it with. The chapter on event listeners returns to this point.
Three ways to create a function value
JavaScript has several syntaxes for creating functions. They all produce function values, but they differ in ways that affect callbacks.
// Function declaration
function square(x) {
return x * x;
}
// Function expression (can be named or anonymous)
const cube = function cubeFn(x) {
return x * x * x;
};
// Arrow function
const half = (x) => x / 2;
console.log(square(4), cube(2), half(9)); // 16 8 4.5| Form | Hoisted? | Own `this`? | Can be used with `new`? | Typical callback use |
|---|---|---|---|---|
| Declaration | Yes, fully | Yes | Yes | Named, reusable handlers |
| Expression | Variable only (per `var`/`let`/`const` rules) | Yes | Yes | Assigned or passed inline |
| Arrow | Variable only | No, uses the surrounding `this` | No | Short inline callbacks |
Hoisting edge case
A function declaration is hoisted with its body, so you can call it before the line where it appears. A function expression stored in a const is not usable before its line. Accessing it earlier throws a ReferenceError, because the binding is in the temporal dead zone.
console.log(early(2)); // 4: declarations are hoisted
function early(x) {
return x * 2;
}
try {
late(2);
} catch (err) {
console.log(err.name); // 'ReferenceError'
}
const late = (x) => x * 2;With var instead of const, the variable is hoisted as undefined. The call then fails with TypeError: late is not a function. That message means you called something that holds a non-function value, and you will see it often when a callback argument is missing or misspelled.
The `this` difference, briefly
Arrow functions take this from the code around them. Regular functions get this from how they are called. When a function becomes a value and gets passed around, the "how it is called" part changes. A later chapter covers this in detail. For now, remember that detaching a method from its object, as in const f = obj.method, detaches its this as well.
Returning functions: closures in miniature
When a function returns another function, the inner one keeps access to the outer function's variables even after the outer call has finished. This combination of a function and the variables it captured is called a closure.
function makeCounter() {
let count = 0;
return function increment() {
count += 1;
return count;
};
}
const counterA = makeCounter();
const counterB = makeCounter();
console.log(counterA()); // 1
console.log(counterA()); // 2
console.log(counterB()); // 1 (separate closure, separate count)Each call to makeCounter creates a new count variable and a new increment function bound to it. Callbacks almost always close over some variables from where they were created. Closures explain both why callbacks work and why some of them misbehave, which is the subject of the closures chapter.
Functions in data structures
Because functions are values, you can choose behavior by looking it up instead of branching. A table of functions can replace a long if/else chain.
const handlers = {
add: (a, b) => a + b,
sub: (a, b) => a - b,
mul: (a, b) => a * b,
};
function calculate(op, a, b) {
const fn = handlers[op];
if (typeof fn !== 'function') {
throw new Error(`Unknown operation: ${op}`);
}
return fn(a, b);
}
console.log(calculate('add', 2, 3)); // 5
console.log(calculate('mul', 4, 5)); // 20The typeof fn !== 'function' guard is a pattern you will reuse. Any function that accepts another function from outside should check it before calling, or at least fail with a clear message.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Code runs immediately instead of later | Passed `fn()` instead of `fn` | Remove the parentheses, or wrap: `() => fn(arg)` |
| `TypeError: x is not a function` | Variable holds `undefined` or another non-function value, often from a typo or a missing argument | Check the name; validate with `typeof` |
| `ReferenceError` calling a function | Called a `const`/`let` function expression before its declaration | Move the definition up or use a declaration |
| Can't remove a handler | Registered an inline function, so no reference to it was kept | Store the function in a variable and pass that same reference |
| `this` is `undefined` inside a passed method | Method detached from its object | Covered in the `this` chapter: `bind` or an arrow wrapper |
Summary
Functions in JavaScript are callable objects. You can assign them, store them, pass them, and return them. Passing a function means passing a reference to it, and that reference stays separate from the value the function returns when it runs. Function equality compares identity, so two identical-looking functions are never equal. A function returned from another function carries its captured variables with it as a closure. Together, these facts are everything a callback needs. The next chapter defines callbacks and shows how to write functions that accept them.
Exercise
What does this code log, and why? function f() { return 'x'; } const g = f; const h = f(); console.log(typeof g, typeof h, g === f);
Show answer
It logs function string true. g holds a reference to the same function object as f, so its type is 'function' and g === f is true. h holds the return value of calling f, which is the string 'x'.
Exercise
A teammate writes button.addEventListener('click', handleClick(42)); and the handler runs once on page load and never on click. Explain the bug and fix it.
Show answer
handleClick(42) is called immediately while the listener is being registered, and its return value (probably undefined) is passed as the listener. The fix passes a function that makes the call later: button.addEventListener('click', () => handleClick(42));. If the listener must be removed later, store that arrow in a variable first and pass the variable to both addEventListener and removeEventListener.
Exercise
Write a function once(fn) that returns a new function. The new function calls fn the first time it is invoked and returns fn's result. Every later invocation returns that same first result without calling fn again.
Show answer
function once(fn) { let called = false; let result; return function (...args) { if (!called) { called = true; result = fn(...args); } return result; }; } It uses a closure over called and result, so each wrapper returned by once tracks its own state. Example: const init = once(() => { console.log('init'); return 1; }); init(); init(); logs 'init' once and returns 1 both times.
Exercise
Why is ((a, b = 1, c) => {}).length equal to 1, and why could this matter when a library inspects a callback's length?
Show answer
length counts declared parameters only up to the first parameter with a default value or a rest parameter, so only a is counted. Some libraries read fn.length to decide how to call a callback. One example is a test framework that checks whether a test function accepts a done argument. Adding a default value to a parameter can change that count and with it the library's behavior.