Product Sum of Special Arrays Can someone please explain why this is correct:
function productSum(array,depth=1) {
    let sum=0;      
    for(let i=0;i&lt;array.length;i++){
        if(Array.isArray(array[i])){                                            
            sum+= productSum(array[i],depth+1)
        }else{
            sum+= array[i];
        }
    }       
    return (depth)*sum;
}

But, following is wrong:
function productSum(array,depth=1) {
    let sum=0;      
    for(let i=0;i&lt;array.length;i++){
        if(Array.isArray(array[i])){                                            
            sum+=(depth)* productSum(array[i],depth+1)
        }else{
            sum+= array[i];
        }
    }       
    return sum;
}

I haven't been able wrap my head around it. Why is does it give wrong answer if I multiply the sum with depth before the for loop on an array ends?
It is clear from the sample output that if there are multiple array items at a depth, we are supposed to multiply the sum with the depth as many times.
Eg. depth 2 is multiplied by the sum twice in the example.
Could someone please break it down for me?
here, you are multiplying the depth of the &quot;parent&quot; array, instead of the nested array.
sum+=(depth)* productSum(array[i],depth+1)

try this
 sum+=(depth+1)* productSum(array[i],depth+1)

multiply it by depth+1