function add(a, b) {
return a + b
}
add(10, 24) // 34
가장 일반적으로 사용하는 방식
const sum = function (a, b) {
return a + b
}
sum(10, 24) // 34
함수를 변수에 할당.
함수는 일급 객체이다: 일반적인 연산이 모두 가능
함수는 다른 함수의 매개변수가 될 수 있고 반환값이 될 수 있고 할당도 가능하다
호이스팅: 변수/함수에 대한 선언을 실행 전에 미리 메모리에 등록하는 작업. 함수 선언문이 마치 코드 맨 앞단에 작성된 것처럼 작동함.
hello() // hello
function hello() {
console.log('hello')
}
함수 선언 전에 함수를 호출했음에도 함수가 미리 만들어진 것처럼 작동
hello() // TypeError: hello is not a function
var hello = function() {
console.log('hello')
}
변수도 호이스팅이 발생하지만, 함수와 다르게 var 변수는 호이스팅 시점에서 undefined로 초기화한다. 따라서 정상적으로 호출되지 않고 에러가 발생한다.
hello() // Uncaught ReferenceError: hello is not defined
const hello = function() {
console.log('hello')
}
const add = new Function('a', 'b', 'return a + b')
add(10, 24) // 34
권장되지 않는다
ES6에서 새롭게 추가된 함수 생성 방식.
const add = (a, b) => {
return a + b
}
const add = (a, b) => a + b
const Person = (name) => {
this.name = name
}
// Person is not a constructor
const person = new Person('이한별')
function hello() {
console.log(arguments)
}
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
hello(1, 2, 3)
const hi = () => {
console.log(arguments)
}
// Uncaught ReferenceError: arguments is not defined
hi(1, 2, 3)
(function (a, b) {
return a + b
})(10, 24) // 34
((a, b) => {
return a + b
})(10, 24) // 34
정의한 순간 즉시 실행되는 함수
const add = function (a) {
return function(b) {
return a + b
}
}
add(1)(3) // 4
함수를 인수로 받거나 결과로 새로운 함수를 반환시키는 함수 (ex. Array.prototype.map)
모던 리액트 Deep Dive | 김용찬 | 위키북스