ThatJsDev

sum(1)(2)(3)(4)..( n)() Frontend Javascript Interview Question

Credits

Visit Akshay Saini's YT channel for full video tutorial.

---

Can you write code for this function: sum(a)(b)(c)....( n)(). This should return the sum of all the numbers a+b+c+..+n.


// Functions in javascripts are First Class Functions
// Functions are like objects
// sum(1)(2)(3).. (n)

// Fist consider it like a function sum(1)(2)() which is called and gives output 3
let sum = function (a) {
  // Sum again gives a function which can be executed by passing an argument inside it let's call it b
  return function (b) {
      return a+b
  }
}

// Now consider it like a function sum(1)(2)(3)() which is called and gives output 6
let sum = function (a) {
  return function (b) {
    return function (c) {
      return a+b+c;
    }
  }
}


// We can see a clear pattern, will solve it recursively
const sum  = function (a) {
  return function (b) {
    if (b) {
      return sum(a+b); // it takes an argument and return a function which again can take an argument.
    }
    return a; // it will keep on adding 1+2+3+4..
  }
};


console.log(sum(1)(2)()); //3
console.log(sum(1)(2)(3)(4)()); //10

---

Subscribe

Subscribe to the newsletter.

---

Bookmark

Unlike life, keyboards do have shortcuts, press COMMAND+D to make this an easily accessible resource by bookmarking it.