Javascript Problems – Sum two numbers

In this problem, I create a function that either takes in two arguments to be added OR is invoked twice to add the numbers.  On line 6, I test to see if there is no argument b.  If there is no argument b, I run an anonymous function that takes in the argument from the second invocation “c”, and adds it to the argument from the first invocation “a”.  Otherwise, on line 11,the function assumes two arguments were passed, adds them, and returns them.

// Write a "sum" function which will work properly when invoked using either syntax below.
// console.log(sum(2, 3)) // 5
// console.log(sum(2)(3)) // 5

function sum(a,b) {
  if(!b) {
    return function(c) {
      return a + c;
  } else {
    return a + b;

console.log(sum(2, 3)) // 5
console.log(sum(2)(3)) // 5


Leave a Reply

Your email address will not be published. Required fields are marked *