Node.js Functions

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

Parameters

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

Scope

Keep names local when possible. Small scopes make code easier to reason about and reduce accidental coupling.

Closures

A closure keeps access to variables from an outer scope. This is useful for factories, handlers, and small stateful utilities.

Practice

  1. Write one function with a default parameter.
  2. Return another function from a factory.
  3. Explain why the inner function still sees outer variables.