Skip to content

J070 Function that Returns a Function

A challenge to understand how functions in ES (ECMAScript) can return other functions and encapsulate logic.

Within your app.js:

Task:

Create a function called findCalculator which randomly returns one of four different functions: addition, subtraction, multiplication, or division.

You can use the following snippet to get a random number between 1 and 4:

let rnd = Math.ceil(Math.random() * 4);

Once you’ve defined findCalculator, you should be able to use it like this:

const calculate = findCalculator();
console.log(calculate(6, 2));

And the result should be either 8 (addition), 4 (subtraction), 12 (multiplication), or 3 (division).

Solution
"use strict";

function findCalculator() {
  let rnd = Math.ceil(Math.random() * 4);

  switch(rnd) {
    case 1:
      return (a, b) => a + b; // addition
    case 2:
      return (a, b) => a - b; // subtraction
    case 3:
      return (a, b) => a * b; // multiplication
    case 4:
      return (a, b) => a / b; // division
  }
}

const calculate = findCalculator();
console.log(calculate(6, 2));

This exercise highlights the power of JavaScript’s first-class functions, where functions can be treated as values and be returned by other functions.