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

148
Visualizações
How to add to a global variable with a functions return value (JavaScript)

I have a callback function which takes two parameter and a global variable that I would like to add to with the value returned from this function. However the variable remains the same. Please help!

let sum = 0;
const myArr = [{name: 'dj', value: '2'}, {name: 'kd', value: '3'}];

function addObjValue(arr, total) {
    arr.forEach(element => {
        const val = element.value;
        total += checkObjValue(val);
        console.log(total);
    })
}

function checkObjValue(x) {
    switch(x) {
        case '2':
            return 1;
            break;
        case '3':
            return 5;
            break;
    }
}

addObjValue(myArr, sum); // sum remains 0
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can make a local variable and save totals there, then just return total value

function addObjValue(arr) {
    let total = 0
    arr.forEach(element => {
        const val = element.value;
        total += checkObjValue(val);
        console.log(total);
    })
    return total
}

And after that make your sum equal to returned value

sum = addObjValue(myArr);

Update One more thing. To get sum from an array you can use reduce method

arr.reduce((totalSum, currenElement) => {
    return totalSum + currenElement.value
}, 0 /*first value of totalSum (by default equal to the first element of the array)*/)
about 4 years ago · Juan Pablo Isaza Relatório

0

Issue:

  • total is scoped under addObjValue so it doesn't add to final sum
  • break inside switch-case is unreachable as it comes after return 1;

You can make below 2 changes to make it work.

let sum = 0;
const myArr = [{name: 'dj', value: '2'}, {name: 'kd', value: '3'}];

function addObjValue(arr, total) {
    arr.forEach(element => {
        const val = element.value;
        total += checkObjValue(val);
    })
    return total; // change 1: returning total
}

function checkObjValue(x) {
    switch(x) {
        case '2':
            return 1;
        case '3':
            return 5;
    }
}

sum = addObjValue(myArr, sum); // change 2: assigned return value back to sum
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