This page looks best with JavaScript enabled

Scope Chaining using Closures in Javascript

 ·   ·  ☕ 1 min read

You can easily chain methods along with variables to find a highly readable, and totally sensible scope chain.

We have seen how closures can be used in Javascript before. Let us see some more practical usage scenarios.

Consider the below closure -

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

const twice = getProduct(2);

console.log(twice(3)); // 6

What do you think will happen if we put more inner functions?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
function getProduct(x) {
  return function(y) {
    return function(z) {
      return function(a) {
        return function(b) {
          return x * y * z * a * b;
        };
      };
    };
  };
}

const prod = getProduct(2)(3)(4)(5)(6);

console.log(prod); // 720

With each iteration, we remember the variable and proceed to the next. We therefore end up multiplying all products from left to the right. We could have done it separately as we did before, or neatly chain it like depicted in the above code.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things