This page looks best with JavaScript enabled

Function of Functions in Javascript

 ·   ·  ☕ 2 min read

Functions are objects in Javascript. So, we could use functions as objects within other functions.

So, the below is valid -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function getProductPlus(x, y) {
  function factoredResult() {
    const factor = 2;
    //console.log("factored : ", x * y * factor);
    return x * y * factor;
  }

  return factoredResult;
}

let prod = getProductPlus(3, 5);
console.log("prod ", prod()); // 30

We call point a variable prod to getProductPlus, and pass arguments.
Then we execute prod(). In other languages this likely implies that the outer function has been executed and has already lost its variables.

However, Javascript behaves differently. It executes the inner function taking variable values that had been supplied to outer function earlier, and provides back the results.

The inner function “closes over” or works together with outer function, regardless of when it is called. This unique function of functions is called ‘closure’ in Javascript, and is super useful.

Closure works because -

  • Javascript remembers the environment in which a closure was created. Inner function is created in the context of and within outer function
  • Reference is maintained to the context until the evaluation is complete. Variables retain values until inner function is evaluated

We see currying functions in Javascript in another post - closure makes similar implementations really easy.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function toPower(x) {
  return function(y) {
    return y ** x;
  };
}

const square = toPower(2);
const cube = toPower(3);

console.log(square(3)); // 9
console.log(cube(2)); // 8

Here, the program remembers the values when we initialize square and cube. We can then use the initiated variables as functions to get the final result.

You might have seen by now that closures have some degree of similarity with objects (as in instances of classes) and methods of objects that retain data specific to objects.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things