Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
Addition assignment did not run as expected in Javascript's recursive functions

For the following functions that use addition assignment, the value of ans is always changed to 1 when an integer greater than 1 is passed

let ans = 0;
function reduce(num){
    if(num == 0){
        return 0;
    }
    ans += reduce(num-1);
    return 1;
}
reduce(5);
console.log(ans); // 1

But when I save the recursive result to another variable first, the function works fine (ans will be changed to num-1)

let ans = 0;
function reduce(num){
    if(num == 0){
        return 0;
    }
    let tmp=reduce(num-1);
    ans += tmp;
    return 1;
}
reduce(5);
console.log(ans); // 4

How does this happen? Is this a feature of Javascript or a bug in the environment?

I have tried similar C codes and they all behave the same

#include<stdio.h>
int reduce(int num);
int ans;
int main(){
    ans = 0;
    reduce(5);
    printf("%d",ans); // 4
}

int reduce(int num){
    if(num == 0){
        return 0;
    }
    int tmp=reduce(num-1);
    ans += tmp;
    // ans += reduce(num-1);
    return 1;
}

Environment:

  • Microsoft Edge 97.0.1072.55
  • JavaScript V8 9.7.106.18
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This happens because in JavaScript ans += reduce(num-1) is evaluated as:

ans = ans + reduce(num-1)

and not as:

ans = reduce(num-1) + ans;

(See (13.15.2) Runtime semantics: evaluation in the ECMAScript specs).

So ans is evaluated before the recursive call is made, and it is that evaluated value that is used as the operand of the addition.

You can avoid such unexpected behaviour by avoiding functions with side-effects. A pure recursive solution would be:

function reduce(num) {
    if (num < 2) {
        return 0;
    }
    return reduce(num-1) + 1;
}
let ans = reduce(5);
console.log(ans); // 4

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda