How to write functions

Declare and call a function

Parameters name incoming values. return sends a result to the caller and ends the function.

function add(left, right) {
  return left + right;
}

const total = add(4, 7);
console.log(total);

Use defaults and validate

A default applies when an argument is omitted or undefined. Validate assumptions near the function boundary.

function greet(name = "friend") {
  if (typeof name !== "string") {
    throw new TypeError("name must be a string");
  }
  return `Hello, ${name}!`;
}
console.log(greet());

Write function expressions and arrows

Functions are values. Arrow functions are concise callbacks but do not have their own this.

const square = function (number) {
  return number * number;
};
const double = number => number * 2;
console.log(square(5), double(5));

Understand scope and design

  • Bindings declared inside a function are local to it
  • A function may read outer bindings through a closure
  • Prefer small functions with one clear responsibility
  • Return data instead of changing unrelated global state