This chapter follows Loops in JavaScript.
Function declarations
A function declaration is hoisted with its body—you can call it before its line in the same scope.
log("ready");function log(msg) { console.log(msg);}In strict modules, top-level declarations are module-scoped, not properties of globalThis.
Function expressions
A function expression produces a value. When bound with const or let, it is not hoisted like a declaration—the name exists only after the initializer runs (TDZ applies).
const multiply = function (a, b) { return a * b;};
const divide = (a, b) => a / b; // arrow, see belowNamed function expressions (const fn = function inner() {}) help stack traces; inner is not visible outside the function.
Arrow functions
Arrow functions (() => {}) have no arguments object, no prototype, and cannot be used as constructors. They lexically bind this—they do not have their own this, arguments, super, or new.target.
const counter = { n: 0, inc() { setInterval(() => { this.n += 1; // `this` is counter }, 1000); },};Use arrows for callbacks when lexical this is desired; use method shorthand or declarations for object methods that others might extract.
Default parameters
Defaults apply when the argument is undefined, not when it is missing only in some edge cases—undefined triggers default; null does not.
function connect(host = "localhost", port = 443) { return `${host}:${port}`;}connect(undefined, 8080); // localhost:8080Defaults are evaluated at call time, left to right, and can reference earlier parameters.
function scale(value, factor = value > 0 ? 1 : -1) { return value * factor;}Rest parameters
Rest (...names) collects remaining arguments into a real array. Prefer rest over arguments in modern code.
function sum(first, ...rest) { return rest.reduce((a, b) => a + b, first);}sum(1, 2, 3); // 6Rest must be the last formal parameter. It works in arrow functions; arguments does not.
The arguments object
In non-arrow functions, arguments is array-like (indexed, has length) but not a true array—no .map unless you copy it.
function legacy() { console.log(arguments.length); const args = [...arguments];}Strict mode and arrow functions push you toward rest parameters for variadic APIs. Generators and async functions have their own rules; rest remains the portable pattern.
Returning and throwing
return ends the function; return await promise in async functions affects error stack and rejection handling in subtle ways—use deliberately in async wrappers.
Function parameters can use destructuring defaults—see the next chapter.
Next: Destructuring and spread.