[JS] => | 화살표 함수 | arrow function

limielife·2024년 11월 16일

JavaScript

목록 보기
8/8

=> ; 화살표 함수(arrow function)

화살표 함수(arrow function)를 정의할 때 사용되는 문법으로 간결하게 함수를 작성

(1)

function 함수이름() {
  //어쩌구
}

(2)

var 함수이름 = function() {
  //어쩌구
}

화살표 함수를 사용하면 이렇게 간단하게 만들 수 있다!

var 함수이름 = () => {
  //어쩌구
}

사용 방법

const 함수이름 = (매개변수) => {
  // 함수의 본문
  return 값;
};
예시
const add = (a, b) => {
  return a + b;
};
console.log(add(2, 3)); // 출력: 5

화살표 함수의 간단한 문법

  1. 매개변수가 하나일 경우: 괄호 () 생략 가능
const square = x => x * x;
console.log(square(4)); // 출력: 16
  1. 본문이 한 줄이고 return만 있을 경우: {}와 return 생략 가능
const add = (a, b) => a + b;
console.log(add(2, 3)); // 출력: 5
  1. 매개변수가 없을 경우: 빈 괄호 () 필요
const greet = () => "Hello, World!";
console.log(greet()); // 출력: "Hello, World!"

화살표 함수 VS function

  1. this 바인딩
    화살표 함수는 자신만의 this를 가지지 않고, 선언된 위치에서의 상위 this를 사용
    즉, this는 정적으로 바인딩됩니다.
function Person() {
  this.age = 0;

  // 화살표 함수: 상위 `this`를 사용
  setInterval(() => {
    this.age++; // Person의 `this`
    console.log(this.age);
  }, 1000);
}

new Person();
일반 function은 자신만의 this를 가지므로, 위 코드에서 일반 함수를 사용하면 this가 undefined가 되어 에러가 발생
  1. arguments 객체
    화살표 함수는 arguments 객체를 제공, 대신 상위 함수의 arguments를 참조
function normalFunction() {
  console.log(arguments); // [1, 2, 3]
}

const arrowFunction = () => {
  console.log(arguments); // ReferenceError: arguments is not defined
};

normalFunction(1, 2, 3);
arrowFunction(1, 2, 3);
profile
Let's look forward to where life leads us 🌿

0개의 댓글