# Types of Functions

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Functions
Source: https://www.devtutorials.ai/learn/javascript/functions/types-of-functions

> Named, anonymous, expression and arrow functions, callbacks and higher-order functions, nested and recursive functions with a base case, and async functions.

## What Are the Types of Functions?

JavaScript lets you write and use functions in several ways.

- **How you write it:** named, anonymous, function expression, arrow.
- **How you use it:** callback, higher-order, nested, recursive.
- **async** functions wait for slow work, like loading data.

**Simple lesson:** a function is a value, like a number. You can store it, pass it, and return it.

### A Real-World Example

A search box on a shop page calls `addEventListener("input", callback)`.
The browser runs your **callback** every time a letter is typed.
The callback shows only the products whose names match.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="A function card called showMatches is handed to the browser. Each time a key is pressed, the browser calls the card back." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="30" y="60" width="140" height="50" rx="8" fill="#fefce8" stroke="#ca8a04" />
    <text x="100" y="90" textAnchor="middle" fontSize="13" fontFamily="monospace" fill="#854d0e">showMatches</text>
    <rect x="330" y="45" width="200" height="80" rx="12" fill="#1e3a8a" />
    <text x="430" y="78" textAnchor="middle" fontSize="13" fill="#ffffff">Browser</text>
    <text x="430" y="100" textAnchor="middle" fontSize="11" fill="#bfdbfe">on each key: call it back</text>
    <rect x="170" y="70" width="40" height="30" rx="6" fill="#fde68a" stroke="#ca8a04">
      <animate attributeName="x" values="170;290;290" keyTimes="0;0.5;1" dur="3s" repeatCount="indefinite" />
    </rect>
    <path d="M330 120 C 260 160, 160 150, 110 112" fill="none" stroke="#16a34a" strokeWidth="2" strokeDasharray="5 4">
      <animate attributeName="stroke-dashoffset" values="40;0" dur="1.2s" repeatCount="indefinite" />
    </path>
    <text x="230" y="158" textAnchor="middle" fontSize="12" fill="#166534">called back on every key press</text>
  </svg>
  <figcaption>You hand the function over. The browser calls it back later.</figcaption>
</figure>

One box below fails on purpose to show endless recursion. Its title says so.

## What You Will Learn

1. Named, anonymous, expression and arrow functions.
2. Callbacks and higher-order functions.
3. Nested functions.
4. Recursive functions and the base case.
5. async functions.

## Named Function

A function with a name after the `function` keyword. The name shows in error messages, which helps debugging.

```js runnable title="A named function and the name JavaScript stores for it"
function applyCoupon(total) {
  return total - 50;
}
console.log(applyCoupon(400));
console.log(applyCoupon.name);
```

Expected output:

```text
350
applyCoupon
```

## Anonymous Function

A function with **no name**. It is used once, usually passed straight into another function.

```js runnable title="An anonymous function passed straight into another function"
const prices = [120, 80, 45];
prices.forEach(function (price) {
  console.log("Price:", price);
});
```

Expected output:

```text
Price: 120
Price: 80
Price: 45
```

## Function Expression

A function stored in a variable. Call it through the variable's name.

```js runnable title="A function stored in a const and called through it"
const addGst = function (price) {
  return price * 1.18;
};
console.log(addGst(200));
```

Expected output:

```text
236
```

Unlike a declaration, it is not hoisted. Define it before you call it.

## Arrow Function

A shorter way to write a function expression, with `=>`.

- One parameter: the `( )` are optional.
- One expression as the body: no `{ }` and no `return` needed.

```js runnable title="The same function written three ways, each shorter than the last"
const double1 = function (n) {
  return n * 2;
};
const double2 = (n) => {
  return n * 2;
};
const double3 = (n) => n * 2;
console.log(double1(5), double2(5), double3(5));
```

Expected output:

```text
10 10 10
```

To return an object from a short arrow, wrap it in `( )`:

```js runnable title="Returning an object needs round brackets around it"
const makeItem = (name, price) => ({ name, price });
console.log(makeItem("Pen", 20));
```

Expected output:

```text
{
  "name": "Pen",
  "price": 20
}
```

## Callback Function

**Callback** = a function you pass to another function, which calls it later.
The same code can do different things, depending on the callback you give it.

```js runnable title="One function, two different callbacks deciding what happens next"
function placeOrder(item, onDone) {
  console.log("Placing order for", item);
  onDone(item);
}
placeOrder("Lunch box", (item) => console.log("Email sent for", item));
placeOrder("Pen", (item) => console.log("SMS sent for", item));
```

Expected output:

```text
Placing order for Lunch box
Email sent for Lunch box
Placing order for Pen
SMS sent for Pen
```

Click handlers and timers are callbacks too: `setTimeout(callback, 1000)` calls `callback` after one second.

## Higher-Order Function

**Higher-order function** = a function that takes a function, or returns one (or both).

```js runnable title="A function that builds and returns other functions"
function makeDiscount(percent) {
  return (price) => price - (price * percent) / 100;
}
const festivalSale = makeDiscount(20);
const memberSale = makeDiscount(10);
console.log(festivalSale(500), memberSale(500));
```

Expected output:

```text
400 450
```

`forEach`, `map` and `filter` on arrays are higher-order functions too.

## Nested Function

A function inside another function. The inner one can read the outer one's variables.

```js runnable title="An inner helper reads the currency of the outer function"
function printBill(items) {
  const currency = "₹";
  function line(name, price) {
    return `${name}: ${currency}${price}`;
  }
  for (const item of items) console.log(line(item.name, item.price));
}
printBill([{ name: "Pen", price: 20 }, { name: "Bag", price: 799 }]);
```

Expected output:

```text
Pen: ₹20
Bag: ₹799
```

## Recursive Function

**Recursive function** = a function that calls itself with a smaller problem.
**Base case** = the condition where it stops calling itself.

```js runnable title="A countdown that calls itself with a smaller number each time"
function countdown(n) {
  if (n === 0) {
    console.log("Sale starts!");
    return;
  }
  console.log(n);
  countdown(n - 1);
}
countdown(3);
```

Expected output:

```text
3
2
1
Sale starts!
```

```js runnable title="Factorial built from a smaller factorial on each call"
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
console.log(factorial(5));
```

Expected output:

```text
120
```

With no base case, it never stops, and JavaScript gives up:

```js runnable expect-error title="A recursive function with no base case never stops"
function forever(n) {
  return forever(n + 1);
}
forever(1);
```

## Async Function

An **async** function can `await` slow work without freezing the page.

- It always returns a **promise** (a value that arrives later).
- `await` waits for that promise and gives you its value.

```js runnable title="An async function returns a promise, and await unwraps it"
async function getPrice(item) {
  return item === "Pen" ? 20 : 0;
}
const promise = getPrice("Pen");
console.log(promise instanceof Promise);
console.log(await promise);
```

Expected output:

```text
true
20
```

The **Async** chapter covers promises in detail.

## Functions on a Web Page

A search box with an **arrow callback** for each key press, a **named** function that draws the list, and a **higher-order** function that builds the test.

```js runnable preview="product-list" title="A live search built from callbacks"
const products = ["Steel bottle", "Lunch box", "Notebook", "Pencil box", "School bag"];
const list = document.querySelector("#products");
const search = document.querySelector("#search");
const status = document.querySelector("#status");

function makeMatcher(text) {
  const wanted = text.toLowerCase();
  return (name) => name.toLowerCase().includes(wanted);
}

function draw(matches) {
  list.innerHTML = "";
  for (const name of products) {
    if (!matches(name)) continue;
    const li = document.createElement("li");
    li.textContent = name;
    list.append(li);
  }
  status.textContent = `${list.children.length} found`;
}

search.addEventListener("input", () => draw(makeMatcher(search.value)));
draw(makeMatcher(""));
console.log("Type 'box' in the search field.");
```

Type `box` in the Preview. The callback runs on every key, and the list shrinks to 2 items.

**Easy way to remember:** a callback is a phone number you leave behind: "call me back when you are done."

## TL;DR

- Functions are values: store them, pass them, return them.
- Arrow: `(n) => n * 2`. Wrap an object result in `( )`.
- Callback = passed in and called later. Higher-order = takes or returns a function.
- Recursion needs a base case, or it never ends.
- `async` functions return promises; `await` unwraps them.

## Try this

In **Higher-Order Function**, add `const clearance = makeDiscount(50);` and print `clearance(500)`. You made a new function without writing a new `function`.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `onDone()` inside the call: `placeOrder("Pen", onDone())` | Pass it with `()` | Pass the name, `onDone` | It runs too early and passes `undefined` |
| `(x) => { x * 2 }` | Arrows always return | `{ }` needs `return` | `undefined` |
| `() => { name: "Pen" }` | That returns an object | Wrap it: `() => ({ name: "Pen" })` | `undefined` |
| Recursion with no base case | It stops by itself | Add a stopping `if` | `RangeError: Maximum call stack size exceeded` |
| Using an async result without `await` | It returns the value | It returns a promise | You see `Promise {}` |

## Quick reference

<div className="tscroll">

| Type | Syntax | Use it for |
|---|---|---|
| Named function | `function tip(bill) { ... }` | a reusable function called by name |
| Anonymous function | `function (bill) { ... }` | a one-off function passed as a value |
| Function expression | `const tip = function (bill) { ... };` | storing a function in a variable |
| Arrow function | `const tip = (bill) => bill * 0.15;` | short functions and callbacks |
| Callback function | `placeOrder("tea", notify)` | telling another function what to do next |
| Higher-order function | `function makeMultiplier(factor) { ... }` | functions that take or return functions |
| Nested function | `function outer() { function inner() { ... } }` | a private helper inside one function |
| Recursive function | `function f(n) { if (n === 0) return; f(n - 1); }` | problems made of smaller copies of themselves |
| Async function | `async function load() { ... }` | work that takes time; always returns a promise |

</div>

## Exercises

## What to Remember

- There are many ways to write a function; arrows are the shortest.
- Passing functions around (callbacks) is how pages react to clicks and typing.
- Recursion needs a base case; async functions need `await`.

Next: **Date Fundamentals**. Create, read and change dates.
