다른 함수에 함수를 전달하거나(=함수의 매개변수로 사용되거나),
함수가 함수를 리턴할 때(=함수 호출 시 함수가 호출되면)는 주로 일반함수보다 익명함수 사용 (일반함수도 사용은 가능함)
그 이유는, 특정 함수가 호출될 때만 쓰이는 함수인데 굳이 일반함수로 해두면 함수가 호출된 후에 익명함수처럼 가비지 컬렉터에 의해 메모리 정리되지 않음
function 함수명(매개변수) {}//!!!! 한 줄 이면 중괄호 생략 가능 (단, return 일 때 중괄호 생략하면 return도 생략해야 함)
const sayHello = nickname => console.log(`${nickname}님, 안뇽?`);
sayHello('메롱');
const add2 = (n1, n2) => n1 + n2;
// const add3 = (n1, n2) => return n1 + n2; <- 불가(return 빼야 함)
// 매개변수가 한 개 라면 매개변수에 ()도 생략 가능
const pow = n => n ** 2;
// 위에 식은 const pow = function (n) { return n ** 2}; 와 같음
| 메서드 | 목적 | 반환값 | 매개변수 설명 |
|---|---|---|---|
map() | 배열의 각 요소를 변환하여 새로운 배열을 만든다. | 새로운 배열 (변환된 결과) | callback(currentValue, index, array)- currentValue: 현재 처리 중인 요소- index (선택적): 현재 요소의 인덱스- array (선택적): map()이 호출된 원본 배열 |
forEach() | 배열의 각 요소에 대해 주어진 함수를 실행한다. | undefined | callback(currentValue, index, array)- currentValue: 현재 처리 중인 요소- index (선택적): 현재 요소의 인덱스- array (선택적): forEach()가 호출된 원본 배열 |
filter() | 배열에서 주어진 조건을 만족하는 요소들만 필터링하여 새로운 배열을 만든다. | 새로운 배열 (조건에 맞는 요소) | callback(currentValue, index, array)- currentValue: 현재 처리 중인 요소- index (선택적): 현재 요소의 인덱스- array (선택적): filter()가 호출된 원본 배열 |
//map()
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
//forEach()
const numbers = [1, 2, 3];
numbers.forEach(num => console.log(num * 2)); // 2, 4, 6
//filter()
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
아래에서 function ()을 호출하려면 arr[1]이 아니라 arr[1]() 입력 !!!!
console.log('======arr 예시 출력값 =========');
const arr = [
{ age: 3, name: '영희' },
function () {
console.log('배열안의 함수!');
}
];
arr[5](); // 출력값 : 배열안의 함수!
arr[5]; // 출력값 없음
console.log(arr[5]); // 출력값 : function
const pooh = arr[5]; // function을 변수에 저장
pooh(); // 출력값 : 배열안의 함수
function callFunction(fn) {
fn();
}
function printSubstract(x) {
const result = x(10, 4); // 함수를 매개변수로 받을 거고, 그 함수에 인자(argument)를 10, 4 로 해서 함수를 호출해라!
console.log(`result: ${result}`);
}
// !!!!!! 함수가 함수를 리턴
const bar = (n1, n2) => () => n1 + n2;
/*
위 함수는 아래와 같은 뜻임
const bar = function (n1, n2) {
return function () {
return n1 + n2;
}
}
*/
const foo = bar(5, 8);
console.log(foo); // !!!! !출력값 : [Function (anonymous)]
const goo = foo();
// console.log(`goo: ${goo}`); // !!!! 출력값 : goo 13