Coding Challenge Practice - Question 90

Published: (December 29, 2025 at 05:33 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

Task

The task is to implement a sum function.

Boilerplate code

function sum(num) {
  // your code here
}

Desired behavior

sum(num) returns a function that remembers the current total, can be called again to add more numbers, and can behave like a number when compared.

function inner(next) {
  return sum(num + next);
}

Each time the function is called, a new sum call is created and the previous value is not modified. JavaScript tries to convert objects to primitives during comparison. Since the result is a function, JS calls valueOf.

inner.valueOf = function () {
  return num;
};

Some environments use toString, so adding it to the function makes it more robust.

inner.toString = function () {
  return String(num);
};

Final code

function sum(num) {
  function inner(next) {
    return sum(num + next);
  }

  inner.valueOf = function () {
    return num;
  };

  inner.toString = function () {
    return String(num);
  };

  return inner;
}

That’s all folks!

Back to Blog

Related posts

Read more »