arrow function을 가장 많이 사용할 때는 callback 함수로 사용할 때이다.
callback 함수란 함수가 함수의 인자로 들어가는 것을 의미한다.
map 메서드는 배열을 반복해주는데, callback 함수에서 반환한 값으로 매 요소를 수정해준다.
map method의 return값은 수정된 값으로 다시 생성된 배열이다.
map
메서드는 그 자체가 for문처럼 배열을
const originalArray = [1,2,3,4,5];
const newArray = originalArray.map(addOne = number => {
return number + 1;
});
console.log(originalArray); // [1,2,3,4,5]
console.log(newArray); // [2,3,4,5,6]
forEach
는 for 대신 사용하는 반복문이다.map
과의 차이는forEach
함수 자체가 return하는 것도 아무것도 없다는 것.forEach
는 단지 for문 대신 사용하는 반복 method이며, forEach 함수를 탈출하고 싶을 때 return을 사용하면 된다.// 예시 1 let startWithNames = []; let names = ['a', 'ab', 'cbb', 'ada']; names.forEach(el => { // names(배열)의 요소에 하나씩 접근 (for문처럼) if (el.startsWith('a')) { // names 요소가 'a'로 시작하면, startWithNames.push(el); // startWithNames 배열에 요소 하나씩 추가 } }); // 예시 2 let hasC = false; let arr = ['a', 'b', 'c', 'd']; arr.forEach(el => { if (el === 'c') { hasC = true; return; // 반복문을 탈출하고 싶을 때 return } }); // 예시 3 let idxOfC = -1; let arr = ['a', 'b', 'c', 'd']; arr.forEach((el, idx) => { // forEach에서 현재 index를 알고 싶으면 두 번째 인자로 받을 수 있다. if (el === 'c') { idxOfC = idx; return; } });