LoginSignup
7
0

More than 5 years have passed since last update.

a => func(a) と func は必ずしも等価というわけではない

Last updated at Posted at 2018-10-17
const funcB = a => funcA(a)
funcA(1)
// => 1
funcB(1)
// => 1

この funcA と funcB は同じだろうか?
a => func(a) は常に func と省略しても大丈夫だろうか?

funcA(1, 100)
// => 101
funcB(1, 100)
// => 1

違うのである。

const funcA = (v1, v2) => {
    return v1 + (v2 || 0)
}

funcB では第一引数以外を無視している点が違いますね。

これによる想定外の動作

const f = callback => {
    return callback({ left: 'pen', right: 'apple' }, null, 2)
}

たとえば上の関数を3通りの呼び出しかたで実行してみよう。

  • f(a => JSON.stringify(a))
  • f(JSON.stringify)
  • f((...a) => JSON.stringify(a))
f(a => JSON.stringify(a))
// => {"left":"pen","right":"apple"}
f(JSON.stringify)
// => {
//      "left": "pen",
//      "right": "apple"
//    }
f((...a) => JSON.stringify(a))
// => [{"left":"pen","right":"apple"},null,2]

JSON.stringify の第二引数以降の option 指定が働くため違った結果になりました。

言いたかったこと

a => funcA(a) だから何も考えずに funcA に省略すると動作が変わる可能性がある ということです。

とはいえ funcA の引数が明確であったり type を使っていたりすればそほど問題は起こらないかと思います。頭の片隅に入れとくべき程度の tips です。

7
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
7
0