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)
}
var sumgets hoisted to the top of the function, so your function is effectivelyvar sum; if( sum === undefined) sum = 0;which is always true.