JavaScript chapters

Chapter 9 of 17

Functions

Try this in our JavaScript Compiler →

Why functions?

A function is a named, reusable block of code. It takes inputs (called parameters), runs some logic, and optionally returns a value. Functions are the single most important tool for keeping a program organised — instead of one giant script, you build a library of small, well-named functions and combine them.

function add(a, b) {
  return a + b;
}
const square = x => x * x;
console.log(add(2, 3), square(5));

Parameters and return values

Parameters are the variables a function declares to receive its inputs. The return value is what the function hands back to whoever called it. A function with no return value is sometimes called a procedure or a void function — it works by side effect (printing, saving, sending) rather than by computing a result.

Scope and pure functions

A function with no hidden state is called "pure" — given the same inputs it always returns the same output. Pure functions are easy to test and reason about. Aim to write pure functions whenever you can, and isolate the impure parts (I/O, randomness, time) at the edges of your program.

Try it yourself

JavaScript Compiler
Output
Code runs in a sandboxed preview inside your browser — your code is saved locally for next time.