Help us understand the problem. What is going on with this article?

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

概要

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 が必要。

参考

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body

簡潔文体 (concise body) においては、単一の式だけが記述できるので、その式が明示的に return される値となります。
しかし、ブロック文体においては、自動的に return はされないので、明示的に return 文を使用する必要があります。
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away