Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
++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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda