Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
++Argument returns different results than argument + 1 when calling a recursive function

Code challenge I was trying to solve:

Write a function that takes in a “special” array and returns its product sum; A “special” array is a non-empty array that contains either integers or other “special” arrays. The product sum of a “special” array is the sum of its elements, where “special” arrays inside it are summed themselves and then multiplied by their level of depth.

The depth of a “special” array is how far nested it is. For instance, the depth of [] is 1; the depth of the inner array in [[]] is 2; the depth of the innermost array in [[[]]] is 3.

I tried solving it like this:

const productSum1 = (array, multiplier=1) => {
    let result = 0;
    for ( const element of array) {
        if ( Array.isArray(element)) {
            result += productSum1(element, ++multiplier)
        } else {
            result += element;
        }
    }
    return result* multiplier;
}

My question is about multiplier++. The value of multiplier would persist after executing the top call on the stack rather than return to its previous value on the previous call. I had to decrement (--multiplier) multiplier in order for it to return the correct value. However, when I used used multiplier + 1, it would return to its previous value after the top call was executed. Why does this happen?

Apologies for my poorly written question. I am very new to programming and I'm sure this could be asked in a much better way.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!