JavaScript by Example

Functions

Declaration vs expression, hoisting, default params, rest params, and dynamic `this`.

Functions are the primary unit of reuse in JavaScript. How you declare them affects hoisting, this binding, and readability.

A function declaration is hoisted - the name and body are available before the line they appear on. A function expression is only available after the assignment is evaluated.

// declaration - works before its definition line
greet("World"); // Hello, World
 
function greet(name) {
  console.log("Hello, " + name);
}
 
// expression - not hoisted; calling it before this line throws
const farewell = function (name) {
  console.log("Goodbye, " + name);
};
farewell("World"); // Goodbye, World

Default parameters provide fallback values when an argument is undefined. They are evaluated at call time, not definition time.

function connect(host = "localhost", port = 5432) {
  console.log(`${host}:${port}`);
}
 
connect();               // localhost:5432
connect("db.prod", 5433); // db.prod:5433

The rest parameter (...args) collects all remaining arguments into a real array. It must be the last parameter.

function sum(first, ...rest) {
  return rest.reduce((acc, n) => acc + n, first);
}
 
console.log(sum(1, 2, 3, 4)); // 10

this inside a regular function is determined at call time - it is the object the function is called on, not where it was defined.

const counter = {
  count: 0,
  increment() {
    this.count++;
    console.log(this.count);
  },
};
 
counter.increment(); // 1
 
const fn = counter.increment;
fn(); // TypeError in strict mode (this is undefined); NaN in sloppy mode (this is globalThis)

In production

Positional parameters past two or three make call-sites unreadable: createUser("Ana", true, false, null, 3) - what does each boolean mean? Destructure an options object instead: createUser({ name, admin, verified, role, retries }). It survives parameter reordering, makes call-sites self-documenting, and lets callers omit optional fields cleanly. Flag it in code review when you see more than three positional args.

Enjoyed this? Get more essays on software craft delivered to your inbox.

Subscribe free