Node.js Functions

Functions package behavior into reusable units. In Node, they also shape callbacks, middleware, and event handlers.

Parameters

JavaScript functions support default parameter values and rest parameters (...args) for variable-length inputs. For functions with more than two optional flags, accept a single destructured options object with defaults so callers never have to remember argument order:

function greet(name, role = "developer") {
  return `${name} is a ${role}`;
}

// Options object pattern for clearer multi-parameter signatures
function createServerConfig({ port = 3000, host = "127.0.0.1" } = {}) {
  return `${host}:${port}`;
}

Scope

Variables declared with const or let are scoped to their enclosing block or function, whereas module-level bindings are scoped to the file (never truly global unless attached to globalThis). Keep state local to the smallest possible scope so concurrent requests in a Node server cannot interfere with each other.

Closures

A closure is created whenever an inner function references variables from its enclosing lexical scope and outlives that outer function's execution. In Node.js, closures are the standard way to build configurable middleware, rate limiters, and dependency-injected handlers without classes:

function createCounter(start = 0) {
  let count = start;          // private state captured by the returned closure
  return function next() {
    count += 1;
    return count;
  };
}

const hit = createCounter(10);
console.log(hit(), hit());    // 11, 12

Practice

Build and test reusable function patterns in Node:

  1. Write a function that accepts a destructured options object with default values.
  2. Create a createLogger(prefix) factory that returns a closure prepending prefix to every message.
  3. Explain why storing per-request state in a module-level variable breaks concurrent HTTP handlers.