0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JS】アロー関数でオブジェクトを返す方法

Last updated at Posted at 2025-01-12

Overview

アロー関数でオブジェクトを返す際は、()でラップする必要があります。

() => ( { key: value } )

() => { key: value } // これはダメ

ここからはすべて蛇足ですが、経緯を書きます。


通常のアロー関数は、() => { return }という構文です。

const func = () => {
  // 処理
  return 
}

ただし単行のアロー関数は、{}return句を使わずとも値を返すことができます。

const sum = (a, b) => a + b

console.log(sum(1, 2)) // 3

JSのオブジェクトは{}で囲って表します。

{ key: value }

オブジェクトを返したい場合は、以下のように書けば・・・あれ?

const func = () => { key: 'value' }

console.log(func()) // undefined

{}がオブジェクトではなく、処理をラップするものとして解釈されてしまうのですね。

ということで、()でラップする必要があるのでした。

const func = () => ( { key: 'value' } )

console.log(func()) // { key: 'value' }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?