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.
Details for javascript
try/catch handles synchronous throws and promises awaited inside its block. An unawaited promise can reject outside the catch. Array.sort mutates and needs a numeric comparator for numeric ordering.
Practice and verify
Change one meaningful value in the example and predict the result before running. Then test a boundary or empty value. Explain what changed and why, rather than only copying the output.