function name(args){
//do something
}
function add(num1,num2){
return num1 + num2
}
add(1,2)
const name = function (args) {
//do somethnig
}
const add = function (num1,num2){
//return num1 + num2
}
add(1,2)
const greeting = function (name = 'Anonymous'){
return 'Hi ${name}'
}
greeting() //Hi Anonymous
const noArgs = function() {
return 0
}
noArgs(1,2,3) //0
const twoArgs = function (arg1,arg2){
return [arg1,arg2]
}
twoArg(1,2,3) //[1,2]
const threeArgs = function(arg1,arg2,arg3) {
return [arg1,arg2,arg3]
}
threeArgs() //[undefined, undefined, undefined]
threeArgs(1) //[1,undefined,undefined]
threeArgs(1,2) //[1,2,undefined]
const restOpr = function(arg1,arg2,...restArgs){
return [arg1,arg2,restArgs]
}
restArgs(1,2,3,4,5) //[1,2,[3,4,5]]
restArgs(1,2) //[1,2,[]]
const spreadOpr = function(arg1,arg2,arg3){
return arg1 + arg2 + arg3
}
const numbers = [1,2,3]
spreadOpr(...numbers) //6
공통점 : 데이터 타입, 함수 구성요소 (이름, 매개변수, 몸통)
차이점
// 함수 표현식
const add = function(args) {}
// 함수 선언식
function sub(args) { }
console.log(typeof add) //function
console.log(typeof sub) //function
add (2,7) // 9
function add (num1,num2) {
return num1 + num2
}
sub(7,2) //Uncaught ReferenceError : Cannot access 'sub' before initialization
const sub = function(num1,num2){
return num1-num2
}
console.log(sub) //undefined
sub(7,2) //Uncaght TypeError :sub is not a function
var sub = function (num1,num2){
return num1-num2
}
const arrow1 = function(name) {
return 'hello, ${name}'
}
// 1. function 키워드 삭제
const arrow2 = (name) => {return 'hello, ${name}'}
//2. 매개변수가 1개일 경우 () 생략 가능
const arrow3 = name => {return 'hello, ${name}'}
//3. 함수 몸통이 return을 포함한 표현식 1개일 경우에 {} & return 삭제
const arrow4 = name => 'hello, ${name}'