Phase 1 · FoundationsModule 7~42 min read

Functions

Package behavior into reusable functions using declarations, expressions, parameters, returns, and arrows.

What you'll learn

Functions name a piece of behavior so you can understand it, test it, and reuse it. Good functions are the main building blocks of maintainable JavaScript.

Declarations and expressions

functions.js
function greet(name) {
  return `Hello, ${name}!`;
}

const shout = function (message) {
  return message.toUpperCase();
};

console.log(greet("Rami"));
console.log(shout("keep going"));

A function declaration has a name and is available throughout its scope. A function expression creates a function value and assigns it to a binding. Functions are values: they can be stored, passed, and returned.

Parameters, arguments, and defaults

A parameter is the name in the definition; an argument is the value supplied at a call site.

parameters.js
function priceWithTax(price, rate = 0.11) {
  return price + price * rate;
}

console.log(priceWithTax(100));
console.log(priceWithTax(100, 0.2));

Note

Missing arguments become undefined. A default parameter runs when the argument is missing or explicitly undefined, but not when it is null.

Return values and early returns

return sends a value to the caller and ends that function call. Without a return statement, a function returns undefined.

validate.js
function percentage(part, whole) {
  if (whole === 0) return null;
  return (part / whole) * 100;
}

console.log(percentage(3, 4));
console.log(percentage(1, 0));

Arrow functions

arrows.js
const square = number => number ** 2;

const describeScore = (name, score) => {
  const status = score >= 70 ? "passed" : "keep practicing";
  return `${name}: ${status}`;
};

console.log(square(6));
console.log(describeScore("Dana", 82));
FormBest fit
Function declarationNamed reusable behavior and clear stack traces
Arrow functionShort callbacks and lexical this
Function expressionA function selected or configured at runtime

Arrows are not shorter syntax for every function

Arrow functions do not have their own this or arguments and cannot be constructors. Those distinctions matter in Phase 2.

Rest parameters

A rest parameter gathers any remaining arguments into a real array. It must be the final parameter.

rest.js
function average(...numbers) {
  if (numbers.length === 0) return 0;
  let total = 0;
  for (const number of numbers) total += number;
  return total / numbers.length;
}

console.log(average(10, 20, 30));

Designing useful functions

  • Give functions verb-based names such as calculateTotal or formatName.
  • Make each function responsible for one coherent job.
  • Prefer returning a value to printing inside reusable logic.
  • Avoid changing data outside the function unless mutation is its explicit purpose.
  • Validate at boundaries and keep the successful path easy to follow.

Pure functions are easy to trust

Given the same arguments, a pure function returns the same result and causes no outside changes. Not every function can be pure, but calculations usually should be.

Mini-project: calculator

calculator.js
function calculate(left, operator, right) {
  if (!Number.isFinite(left) || !Number.isFinite(right)) return "Invalid number";

  switch (operator) {
    case "+": return left + right;
    case "-": return left - right;
    case "*": return left * right;
    case "/": return right === 0 ? "Cannot divide by zero" : left / right;
    default: return "Unknown operator";
  }
}

console.log(calculate(12, "*", 4));
console.log(calculate(10, "/", 0));

Recap & quick check

Key takeaways

  • Function declarations, expressions, and arrows all create callable values.
  • Parameters receive arguments; defaults handle missing or undefined arguments.
  • return ends the call and supplies its result.
  • Rest parameters collect extra arguments into an array.
  • Small, focused, value-returning functions are easier to combine and test.

Quick check

1. What does a function return when it has no return statement?

2. What does ...numbers create in a parameter list?

3. Which arrow has an implicit return?

4. What makes a function pure?