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"));
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.
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; }