function add(x, y){
return x + y;
}
console.log(add(3, 5)); // 8
ReferenceError
// 함수 작성 후 호출한 경우
const add = function(x, y){
return x + y;
}
console.log(add(3, 5)); // 8
// 함수 작성보다 호출을 먼저한 경우
console.log(add(3, 5)); // ReferenceError: add is not defined
const add = function(x, y){
return x + y;
}
// 화살표 함수로 작성
const add = (x, y) => x + y;
console.log(add(3, 5)); // 8
괄호로 둘러싸인 익명함수
전역범위를 오염시키는 것 뿐만 아니라 IIFF 내부의 변수에 접근하는 것을 방지
즉시 실행 함수를 실행하는 괄호
JS 엔진은 함수를 즉시 해석해서 실행함
IIFF를 변수에 할당하면 IIFF 자체는 저장되지 않고, 함수가 실행된 결과만 저장됨
(function () {
let x = 3;
let y = 5;
return x + y;
}()); // 8
global scope
가 하나이며 global scope
에 선언된 변수나 함수는 코드 내의 어디서든지 접근이 가능하다는 특징이 있다.모듈 시스템의 보급
스코프 및 변수 관리의 향상
let
과 const
를 사용하여 블록 스코프
변수를 선언할 수 있으므로, 스코프 누출과 같은 문제를 방지할 수 있다.코드 가독성과 유지보수성
const std = {
name : 'song',
num : 20231205,
sayHi : function(){
console.log(`안녕, 나는 ${this.name}라고 해`);
}
}
const std = {
name : 'song',
num : 20231205,
sayHi : () => {
console.log(`안녕, 나는 ${this.name}라고 해`);
}
}
const std = {
name : 'song',
num : 20231205,
sayHi(){ // 기존 `sayHi : function(){`에서 `: function`이 생략된 모습
console.log(`안녕, 나는 ${this.name}라고 해`);
}
}
📝참고) https://velog.io/@thdgusrbek/일반함수-vs-화살표-함수Arrow-function