Function
🔵 함수 선언식과 표현식
함수 선언식
- statement, declaration
- 함수를 별도의 변수에 저장하지 않는다
- 반드시 이름을 지어줘야 한다
function add(num1,num2) {
return num1 + num2
}
add(2,3)
함수 표현식
- 함수를 변수에 저장하여 사용한다.
- 함수 이름이 있어도 되고 없어도 된다. (그러나 이름을 꼭 지어주자!)
- 이름이 있으면 콜스택에 해당 이름으로 쌓이므로 디버깅 시 유용하다.
- 이름이 없는 함수(익명함수)는 콜스택에 익명함수라고 뜬다!
const sub = function sub(num1, num2) {
return num1 - num2
}
sub(7,2)
기본 인자 설정
const greeting = function greetPolitely(name = 'nobody') {
return `hello, ${name}`
}
IIFE
- Immediately Invoked Function Expression
- 즉시 함수를 실행하는 방식
(function callRightAway() {
return '나는 바로 실행되지!'
}())
선언식 vs 표현식
- 선언식은 hoisting이 발생하고 정상적으로 동작한다.
- 표현식은 hoisting시 에러가 발생한다.
hi()
function hi() {
console.log('hi')
}
bye()
const bye = function byePolitely() {
console.log('bye')
}
🔵 화살표함수
- Arrow Function
- function 키워드와 중괄호를 줄이기 위한 brandNew 문법
- 화살표 함수는 function 키워드를 생략해도 된다.
- 화살표함수는 매개변수가 단 하나라면 소괄호도 생략 가능하다.
- 화살표 함수는 바디에 표현식이 딱 한 줄이라면 중괄호와 return도 생략 가능하다.
const arrowFunc = function arrowFunc(name) {
return `Hello! ${name}`
}
const arrowFunc = (name) => {
return `Hello! ${name}`
}
const arrowFunc = name => {
return `hello! ${name}`
}
const arrowFunc = name => `hello! ${name}`
const myArrowFunc = function myArrowFunc(name,age) {
return `${name} ${age}`
}
const myArrowFunc = (name,age) => {
return `Hello! ${name} ${age}`
}