Can someone break down the stack for the following code? How is it calculating? What is happening inside the parenthesis?
I understand that arr[n-1] is calling the element from array by index value, and multiply it with the function. However what does the first ‘n’ inside the parenthesis stand for? And what is happening between the ‘arr’ and the first ‘n-1’ inside parenthesis? Are they multiplying?
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}
multiply(arr, n - 1) * arr[n - 1] will give the product of the value returned by multiply(arr, n - 1) and the value of arr[n - 1] element.
’ n ’ is the variable we pass to the function as an argument( function multiply(arr, n) {...} ). Whereever you find it within the function body, it refers to that value. n-1 would give us that value subtracted by 1.
You are asking what is happening between arr and n-1 by calling multiply(arr, n - 1) . You can determine that by looking at the multiply function body. There you can see how the arguments are used to return a value.