자바스크립트 arrow function 에서 객체 리턴

이한재·2023년 2월 14일

Code

const foo = () => {
  name: 'hanjae',
  sayHi: () => { console.log('hi') }
}

const result = foo()
console.log(result)

Output

sayHi: () => { console.log('hi') }
       ^

SyntaxError: Unexpected token ':'

arrow funciton 에서 객체를 리턴하기 위해서 위의 코드처럼 하면 될거라고 생각을 샜지만
자바스크립트 에서 중괄호 안에서 바로 객체를 리턴하려고하면 문법 에러가 난다.

그래서 arrow function 에서 객체를 리턴하기 위해서는 다음과 같이 수정해야 한다.

Code

const foo = () => ({
  name: 'hanjae',
  sayHi: () => { console.log('hi') }
})

const result = foo()
console.log(result)

Output

{ name: 'hanjae', sayHi: [Function: sayHi] }

핵심은 arrow function 의 코드블락을 나타내는 중괄호를 소괄호로 감싸주게되면
객체를 리턴 할 수 있게 된다.

profile
이한재입니다

0개의 댓글