0

let adder = () => {
  if (sum === undefined) {
    var sum = 0
  }
  sum = sum + 10
  console.log(sum)
  if (sum >= 100) {
    return sum
  }
  adder()
}

Please explain why the sum = 0 every time the recursive function is being activated? Why doesn't it accumulate?

2
  • 3
    var sum gets hoisted to the top of the function, so your function is effectively var sum; if( sum === undefined) sum = 0; which is always true. Commented Mar 30, 2020 at 14:23
  • 1
    Pass the value you want to accumulate to the next call of the function. Commented Mar 30, 2020 at 14:27

2 Answers 2

1

How about utilising the closure property?

const adder = (sum = 0) =>
  () => ++sum

const a = adder()
const b = adder()

console.log(a(), a(), a()) // 1 2 3
console.log(b(), b(), b()) // 1 2 3
console.log(a(), a(), a()) // 4 5 6
console.log(b(), b(), b()) // 4 5 6

Or give the adder a parameter -

const adder = (sum = 0) =>
  (n = 1) => sum += n

const a = adder()
const b = adder()

console.log(a(10), a(10), a(10)) // 10 20 30
console.log(b(), b(), b()) // 1 2 3
console.log(a(), a(), a()) // 31 32 33
console.log(b(), b(), b()) // 4 5 6

Sign up to request clarification or add additional context in comments.

Comments

0

Variables in javascript are always scoped inside the function they're called from. If you define a sum variable inside a function and call a function, even if it's the same function, that function will not have access to the variable. You can, however, define a global variable, and the inner function will have access to it. However, this is not recommended and goes against the concept of recursion.

Solution 1 (global variable, not recommended):

// note how this is declared outside of any function
var sum;
let adder = () => {
  if (sum === undefined) {
    // the var here is gone to avoid redeclaring at a local scope
    sum = 0
  }
  sum = sum + 10
  console.log(sum)
  if (sum >= 100) {
    return sum
  }
  // we also return the value
  return adder()
}

Solution 2 (proper recursion, recommended):

// note how sum is an argument now
let adder = sum => {
  if (sum === undefined) {
    sum = 0
  }
  sum = sum + 10
  console.log(sum)
  if (sum >= 100) {
    return sum
  }
  // we pass sum in as an argument and return it
  return adder(sum)
}

2 Comments

@Aplet123, Thank you! I get the idea. Could you also explain why undefined is being returned when sum reaches 100 in case I use a recursive function adder(sum) without return in a solution 2.
The last adder call returns 100, but that's not being returned by the previous adder calls, so it just defaults to undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.