Basic · 3 of 12 · 15 min read
Functions
Declarations, expressions and arrows, what first-class really buys you, and the parameter features worth knowing by heart.
- Functions
A function is a value. That one fact — not the syntax — is what makes callbacks, closures, higher order functions and most of the language’s patterns possible.
The four forms
// 1. Declaration — hoisted with its body
function add(a, b) {
return a + b;
}
// 2. Expression — only the variable is hoisted
const subtract = function (a, b) {
return a - b;
};
// 3. Named function expression — the name is visible only inside
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1); // `fact` works here, nowhere else
};
// 4. Arrow — no `this`, no `arguments`, no `new`
const multiply = (a, b) => a * b;
console.log(add(2, 3), subtract(5, 1), factorial(4), multiply(3, 3)); // 5 4 24 9
// console.log(typeof fact); // "undefined" — the inner name does not leak
| Declaration | Expression | Arrow | |
|---|---|---|---|
| Usable before its line | yes | no — TypeError or TDZ |
no |
Own this |
yes | yes | no — takes the outer one |
arguments object |
yes | yes | no |
Usable with new |
yes | yes | no |
Has a prototype property |
yes | yes | no |
| Good as an object method | yes | yes | no |
| Good as a callback inside a method | no | no | yes |
console.log(hoisted()); // "works" — the whole function moved up
function hoisted() { return 'works'; }
// console.log(notHoisted()); // TypeError: notHoisted is not a function
var notHoisted = function () { return 'nope'; };
The error type is the tell: TypeError means the name exists and holds undefined;
ReferenceError means it does not exist at all.
Arrow functions
Shorter, but the real differences are semantic.
const double = (n) => n * 2; // implicit return
const noArgs = () => 'hi'; // empty parentheses are required
const pair = (a, b) => ({ a, b }); // an object literal needs parentheses
const block = (n) => { // braces mean a body, so `return` is required
const doubled = n * 2;
return doubled;
};
console.log(double(2), pair(1, 2), block(3)); // 4 { a: 1, b: 2 } 6
The braces trap is the most common beginner bug in modern JavaScript:
const broken = (n) => { n * 2 }; // a block containing a useless expression
const fixed = (n) => n * 2;
console.log(broken(5), fixed(5)); // undefined 10
And this is the difference that matters:
const counter = {
count: 3,
regular() { return this.count; }, // `this` is the object
arrow: () => this?.count, // `this` is the module scope — undefined
late() {
return [1].map(() => this.count); // an arrow here is correct: it keeps `this`
},
};
console.log(counter.regular(), counter.arrow(), counter.late()); // 3 undefined [3]
Method shorthand for methods, arrows for callbacks inside them. That one rule covers almost every case.
Parameters
// Defaults — applied for `undefined`, never for `null`
function greet(name = 'there', greeting = 'Hi') {
return `${greeting} ${name}`;
}
console.log(greet(), greet('Ana'), greet(undefined, 'Hola'), greet(null));
// "Hi there" / "Hi Ana" / "Hola there" / "Hi null"
// A default can use an earlier parameter, but not a later one
function range(start = 0, end = start + 10) { return [start, end]; }
console.log(range(), range(5)); // [0, 10] [5, 15]
// Rest — a real array of everything left over, and it must be last
function sum(first, ...others) {
return others.reduce((total, n) => total + n, first ?? 0);
}
console.log(sum(1, 2, 3)); // 6
// Destructured parameters — named arguments, in effect
function createUser({ name, role = 'member' } = {}) {
return `${name} (${role})`;
}
console.log(createUser({ name: 'Ana' })); // "Ana (member)"
The = {} on that last one is not decoration: without it, calling createUser() throws, because
you cannot destructure undefined.
function strict({ a }) { return a; }
// strict(); // TypeError: Cannot destructure property 'a' of undefined
function safe({ a } = {}) { return a; }
console.log(safe()); // undefined
JavaScript does not check arity. Extra arguments are ignored and missing ones are undefined:
function two(a, b) { return [a, b]; }
console.log(two(1), two(1, 2, 3)); // [1, undefined] [1, 2]
console.log(two.length); // 2 — parameters before the first default or rest
arguments is the old way to reach the extras. Rest is better in every way, and arrows do not
have arguments at all:
function old() { return Array.from(arguments); } // array-like, needs converting
const modern = (...args) => args; // already an array
console.log(old(1, 2), modern(1, 2)); // [1, 2] [1, 2]
First-class, concretely
Functions are values, so they go anywhere a value goes:
const greet = (name) => `Hi ${name}`;
const inAVariable = greet; // assigned
const inAnArray = [greet]; // stored
const inAnObject = { handler: greet }; // a property
const passed = ['Ana'].map(greet); // passed as an argument
function makeGreeter(greeting) { // returned from a function
return (name) => `${greeting} ${name}`;
}
console.log(inAnArray[0]('A'), inAnObject.handler('B'), passed, makeGreeter('Hola')('C'));
// "Hi A" "Hi B" ["Hi Ana"] "Hola C"
They are objects too, with their own properties:
function named(a, b) {}
console.log(named.name, named.length); // "named" 2
named.callCount = 0; // you can attach things to them
console.log(typeof named, named instanceof Object); // "function" true
That is what “first-class” means, and it is why the array methods, promises, event listeners and every pattern in this guide can take behaviour as an argument.
Returning
Every function returns something — undefined when you do not say otherwise.
function nothing() {}
console.log(nothing()); // undefined
And the one piece of syntax that silently breaks a return: a line break after return. Automatic
semicolon insertion closes the statement before your value.
function broken() {
return
{ ok: true }; // unreachable; a semicolon was inserted after `return`
}
function fixed() {
return {
ok: true, // the brace must be on the same line
};
}
console.log(broken(), fixed()); // undefined { ok: true }
IIFE
A function expression invoked immediately. Before modules it was the only way to get a private
scope; now it mostly appears in older code and in top-level await workarounds.
const result = (function () {
const secret = 42; // never reachable from outside
return secret * 2;
})();
console.log(result); // 84
// console.log(secret); // ReferenceError
Common mistakes
Braces on an arrow that was meant to return
Mistake. items.map((i) => { i.price * 2 }).
Why it fails. The braces make a body, the expression’s value is discarded, and the result is an
array of undefined — with no error anywhere.
What to do instead. Drop the braces, or add return. For an object literal, wrap it:
(i) => ({ id: i.id }).
An arrow as an object method
Mistake. const o = { n: 1, get: () => this.n }.
Why it fails. The arrow took this from the surrounding scope, which in a module is
undefined. The object is never consulted.
What to do instead. Method shorthand: get() { return this.n }.
Relying on hoisting to order a file
Mistake. Calling functions above where they are declared.
Why it fails. It works for declarations and breaks the moment one is refactored into a const
arrow — a very common, very confusing change.
What to do instead. Define before use, and treat hoisting as something to read, not depend
on.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
An arrow function has two possible body forms, and they do not behave the same way.
This should double its argument but logs undefined. What is wrong?
const double = (n) => { n * 2 };
console.log(double(4)); // undefinedArrow functions differ from regular functions in several ways. Which difference comes up most often in real code?
What does it mean that functions are **first-class** in JavaScript?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.