LoginSignup
1
0

More than 3 years have passed since last update.

JavaScript の arrow function に return が必要なケース

Last updated at Posted at 2019-11-13

概要

arrow function を使って return が必要なケースと必要でないケースがあったのを忘れていたので書いておきます。

サンプル

  • (arg => ) の場合は return はいらない。
const keys = ['a', 'b']
const text = 'aaaaa'

const result = keys.filter(key => text.includes(key));

console.log(result);
> [ 'a' ]
  • (arg => {}) の場合は return が必要。
const keys = ['a', 'b']
const text = 'aaaaa'

const result2 = keys.filter(key => {
  text.includes(key);
});

console.log(result2);
> []

const result3 = keys.filter(key => {
  return text.includes(key);
});

console.log(result3);
> [ 'a' ]

まとめ

curly brackets(braces) を使う際は return が必要。

参考

簡潔文体 (concise body) においては単一の式だけが記述できるのでその式が明示的に return される値となります
しかしブロック文体においては自動的に return はされないので明示的に return 文を使用する必要があります
1
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
1
0