초기값을 설정하지 않으면 첫 번째 요소에는 콜백 함수가 실행되지 않는다.
[0, 1, 2, 3, 4].reduce(
function (accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue;
},
);
const array = [1, 2, 3, 4];
// 화살표 함수 사용
const sum = array.reduce(
(accumulator, currentValue, currentIndex, array) => accumulator + currentValue,
initialValue
);
let array = [0, 1, 2, 3];
// 함수 표현식 사용
const sum = array.reduce(function (accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue;
}, initialValue);
배열의 요소를 순회하며 로직이 실행되고 하나의 결과 값(accumulator)을 반환한다.
생략할 경우 첫 번째 요소가 초기값으로 자동 설정되고 콜백 함수는 건너뛴다. 콜백 함수는 두 번째 요소부터 적용된다.
const array = [1, 2, 3, 4];
const result = array.reduce(
(accumulator, currentValue) => accumulator + currentValue + 1,
0 // 초기값으로 0을 설정
);
console.log(result);
이 코드의 진행 과정:
const array = [1, 2, 3, 4];
const result = array.reduce(
(accumulator, currentValue) => accumulator + currentValue + 1
// 초기값을 제공하지 않음
);
console.log(result);
진행 과정:
초기값이 없을 경우, reduce 메서드는 배열의 첫 번째 요소를 accumulator의 초기값으로 사용하고, 두 번째 요소부터 연산을 시작한다
초기값이 없으므로, 최종 결과에서 한 번의 1이 덜 더해져 결과적으로 13이 된다.
초기값을 설정하지 않으면 첫 번째 요소에는 콜백 함수가 실행되지 않는다.