# Functions

> Packaging a piece of logic so you can reuse it.

Source: https://aminbytes.dev/bytes/programming/functions/


A **function** takes inputs, does some work and usually returns a result.

## Defining a function

```ts {title="math.ts"}
export function add(a: number, b: number): number {
  return a + b;
}

add(2, 3); // 5
```

## Pure functions

A function is *pure* when the same inputs always give the same output and it changes nothing outside itself. Pure functions are easy to test.

> [!TIP]
> When a function is hard to test, it's often doing two things. Try splitting it.


## Byte check

1. When is a function **pure**?
   - When it has no parameters
   - **When the same inputs always give the same output and it changes nothing outside itself** (correct)
   - When it returns a number
   That's what makes pure functions easy to test.

2. A function is hard to test. What's a common reason?
   - It's too short
   - **It's doing two things** (correct)
   - It returns a value
   Try splitting it into two smaller functions.


