함수는 반복될 수 있는 작업을 미리 정의해두는 것이다.
input을 받아 output을 반환(return)한다.
function add(x, y) { // x,y : 매개변수(parameter), 인자
return x + y; // ⭐️ 값을 반환
// 특정 값을 반환하는 함수는 return문 필요함
}
let z = add(2, 3); // 2,3 : 인수
console.log(z); // 5
function isOdd (x) {
return !!(x % 2);
}
let num = 12;
console.log(
`${num}(는)은 ${
isOdd(num) ? '홀' : '짝'
}수입니다.`
);
let currentTemp = 24.5;
function logCurrentTemp () {
console.log(`현재 온도는 섭씨 ${currentTemp}도입니다.`);
}
console.log('반환값:', logCurrentTemp());
return 문이 정의되어 있지 않으면 undefined 반환함
👉 console.log 실행 뒤 undefined가 뜨는 이유
함수는 실행문보다 나중에 정의하는 것이 가능함
변수나 상수는 불가능(var 제외)하고 오직 함수만 가능.
console.log(add(2, 7));
function add (x, y) {
return x + y;
}
오직 function으로 선언된 함수만 호이스팅 된다. 엔진의 코드 실행 전에 미리 생성되기 때문이다.
function add (x, y) {
return x + y;
}
console.log(add(2, 7));
const subt = function (x, y) {
return x - y;
}
console.log(subt(7, 2));
기존 함수를 재정의하는 것도 가능함
function add (x, y) {
return x + y;
}
console.log(add(2, 7));
// 💡 기존의 함수를 재정의하는것도 가능
add = function (x, y) {
console.log(`${x}와 ${y}를 더합니다.`);
console.log(`결과는 ${x + y}입니다.`);
return x + y;
}
console.log(add(2, 7));
// 한 줄 안에 값만 반환시
const mult = (x, y) => x * y;
console.log(mult(2, 7));
// 두 줄 이상의 작업이 있을 시
const mult = (x, y) => {
console.log(`${x}와 ${y}를 곱합니다.`);
console.log(`결과는 ${x * y}입니다.`);
return x * y; // return 필수
};
console.log(mult(2, 7));
// 인자가 하나일 때는 괄호 없이 선언 가능
const pow = x => x ** 2;
console.log(pow(3));
❗️블록문에 들어가는 화살표 함수는 return
문 필수❗️
화살표 함수는 function 으로 선언된 함수와 기능 차이가 있음
함수를 변수와 같이 다루는 개념이며 자바스크립트의 함수는 객체로 본다.
// ⭐️ 함수의 자료형
function addNumbers (a, b) { return a + b; }
console.log(typeof addNumbers); // function
function isOddNum (number) {
console.log(
(number % 2 ? '홀' : '짝')
+ '수입니다.'
);
return number % 2 ? true : false;
};
const checkIfOdd = isOddNum; // 뒤에 괄호 없음 유의
console.log(checkIfOdd(23));
let x = 7, y = 3;
let func1 = (a, b) => a + b;
let func2 = (a, b) => a - b;
console.log(func1(x, y), func2(x, y));
func1 = func2
console.log(func1(x, y), func2(x, y));
let person = {
name: '홍길동',
age: 30,
married: true,
introduce: function (formal) {
return formal
? '안녕하십니까. 홍길동 대리라고 합니다.'
: '안녕하세요, 홍길동이라고 해요.';
}
};
console.log(person.introduce(true));
console.log(person.introduce(false));
let person = {
name: '홍길동',
age: 30,
married: true,
introduce: function () {
return `저는 ${this.name}, ${this.age}살이고 `
+ `${this.married ? '기혼' : '미혼'}입니다.`;
}
}
console.log(person.introduce());
객체의 다른 프로퍼티에 접근할 때 : this
사용함.
📌 객체 리터럴의 프로퍼티에 this
를 사용할 때는 화살표 함수를 권장하지 않음.
let arithmetics = [
(a, b) => a + b,
(a, b) => a - b,
(a, b) => a * b,
(a, b) => a / b
];
for (arm of arithmetics) {
console.log(arm(5, 3));
}
함수가 다른 함수를 인자로 전달받음
let list = [1, 2, 3, 4, 5];
function doInArray (array, func) {
for (item of array) {
func(item);
}
}
// console.log - console이란 객체에서 log란 키에 할당된 함수
doInArray(list, console.log);
doInArray
: 고차함수
console.log
: 콜백함수
function doNTimes (func, repeat, x, y) {
let result = x;
for (i = 0; i < repeat; i++) {
result = func(result, y);
}
return result;
}
console.log(
doNTimes((x, y) => x * y, 3, 5, 2),
doNTimes((x, y) => x / y, 3, 5, 2),
);
// calculate
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const multiply = (a, b) => a * b;
// evaluate
const isOdd = (number) => !!(number % 2);
const isPositive = (number) => number > 0;
function calcAndEval (calc, eval, x, y) {
return eval(calc(x, y));
}
console.log(
calcAndEval(add, isOdd, 5, 7),
calcAndEval(subtract, isPositive, 5, 7),
calcAndEval(multiply, isOdd, 5, 7)
);
function getIntroFunc (name, formal) {
return formal
? function () {
console.log(`안녕하십니까, ${name}입니다.`);
} : function () {
console.log(`안녕하세요~ ${name}이라고 해요.`);
}
}
const hongIntro = getIntroFunc('홍길동', true);
const jeonIntro = getIntroFunc('전우치', false);
hongIntro();
jeonIntro();
필요한 인자보다 적은 수의 인자를 받으면, 나머지 인자를 인자로 받는 다른 함수를 반환함.
// 기존의 코드
function addMultSubt (a, b, c, d) {
return (a + b) * c - d;
}
const addMultSubt2 = (a, b, c, d) => (a + b) * c - d;
console.log(
addMultSubt(2, 3, 4, 5),
addMultSubt2(2, 3, 4, 5),
);
// ⭐ 커링으로 작성된 함수
function curryAddMultSubt (a) {
return function (b) {
return function (c) {
return function (d) {
return (a + b) * c - d;
}
}
}
}
const curryAddMultSubt2 = a => b => c => d => (a + b) * c - d;
console.log(
curryAddMultSubt(2)(3)(4)(5),
curryAddMultSubt2(2)(3)(4)(5)
);