Types of Functions

By Syncfusion®, Inc. · Last updated

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.

showMatches

Browser on each key: call it back

called back on every key press

You hand the function over. The browser calls it back later.

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.

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:

350
applyCoupon

Anonymous Function

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

An anonymous function passed straight into another function

const prices = [120, 80, 45];
prices.forEach(function (price) {
  console.log("Price:", price);
});

Expected output:

Price: 120
Price: 80
Price: 45

Function Expression

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

A function stored in a const and called through it

const addGst = function (price) {
  return price * 1.18;
};
console.log(addGst(200));

Expected output:

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.

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:

10 10 10

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

Returning an object needs round brackets around it

const makeItem = (name, price) => ({ name, price });
console.log(makeItem("Pen", 20));

Expected output:

{
  "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.

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:

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).

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:

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.

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:

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.

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:

3
2
1
Sale starts!

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:

120

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

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.

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:

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.

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

MistakeWrong ideaCorrect ideaWhat goes wrong
onDone() inside the call: placeOrder("Pen", onDone())Pass it with ()Pass the name, onDoneIt runs too early and passes undefined
(x) => { x * 2 }Arrows always return{ } needs returnundefined
() => { name: "Pen" }That returns an objectWrap it: () => ({ name: "Pen" })undefined
Recursion with no base caseIt stops by itselfAdd a stopping ifRangeError: Maximum call stack size exceeded
Using an async result without awaitIt returns the valueIt returns a promiseYou see Promise {}

Quick reference

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

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.