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

224
Visualizações
Console log in Reduce() returning NaN

This function sums the lengths of all array elements and it works by returning the final value, but using console.log returns the length of the first element and NaN for the rest. Why?

function test(s) {
  return s.split(' ').reduce((a, b) => {
      console.log(a + b.length)
    }, 0);
}

console.log(test("aa aaa aaaa"));

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your issue

a will always have the value that is returned from the previous iteration or the initial value 0. Therefore in the first iteration it is 0 + b.length which results in 2. But then you don't return anything, therefore the return type is undefined. Therefore in the second iteration you have undefined + 2 which results in NaN and that for every other iteration. As you also don't return anything in the last iteration, the return type in the last iteration is undefined and your console.log() at the end will print undefined.

The solution

You need to return the value so it is used for the next iteration.

function test(s) {
  return s.split(' ').reduce((a, b) => {
      return a + b.length
    }, 0);
}

console.log(test("aa aaa aaaa"));
.as-console-wrapper { max-height: 100% !important; top: 0; }

You could also remove the curly braces for a more concise syntax:

function test(s) {
  return s.split(' ').reduce((a, b) => a + b.length, 0);
}

console.log(test("aa aaa aaaa"));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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