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

222
Views
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 answers
Answer question

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 Report
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!