Spacecase
Spacecase

Reputation: 37

Why does my variable get reinitialized to its original value everytime I go through the recursive iteration, but somehow keep the new value

So I just solved a code challenge on AlgoExpert and I was trying to get a deeper understanding of why my code works so i used PythonTutor to visualize the execution of the code, and I am curious to know why each time a recursive call is made arraySum re-initializes to 0 but somehow keeps the value it had previously that consisted of the sum of elements in the array.

Here is the problem I solvedenter image description here

Here is my code:

function productSum(array, multiplier=1) {
    let arraySum = 0;
    array.forEach(el => Array.isArray(el) ? arraySum+=productSum(el, multiplier+1) : arraySum += el)
    return arraySum * multiplier
}

productSum([5, 2, [7, -1], 3, [6, [-13, 8], 4]])

Here is a link to the visualization in PythonTutor

Upvotes: 0

Views: 105

Answers (2)

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

Your algorithm contains recursive calling: your productSum at times calls itself again with different arguments, at a deeper level in your data structure.

Each call gets its own call frame, with its own unique scope. Your let arraySum = 0 is defined within the function (scope), therefore every call has its own arraySum (initialized to 0) apart from other calls.

I've made another diagram, where every box/oval is a call frame:

Call visualization

Didn't display the multiplication part.

Every call frame has its own scope with its own array/multiplier/arraySum variables. Every call starts with arraySum = 0, uses .forEach to add to this variable, then returns the value stored in the variable. That's why in the Python visualizer you see arraySum become 0 at times. It's not that an actual arraySum somewhere becomes 0, it's because you're looking at a brand new function call, right after the let arraySum = 0 statement.

Changing arraySum in one scope has no affect on the arraySum of another scope, even if both scopes are for the same function (but different function call!).

Upvotes: 1

trincot
trincot

Reputation: 350345

It becomes clear when you realise every execution of productSum has its own arraySum variable. Although the name is each time the same, it really is a variable that is unrelated to the other variables out there (in the recursion tree) that happen to have the same name.

Each time a recursive call is made, the caller's productSum ends up on a stack frame, from where it is restored when the recursive call returns, and then the returned value is added to its own productSum.

And so a value is accumulating while backtracking out of recursion, and all those different productSum variables each play a little role in carrying an intermediate result, until it was returned to the caller, who accumulated it further, ...etc.

Upvotes: 2

Related Questions