ES6: Why does my misplacement of the parenthesis still produce same result?

问题: I noticed that I had a type in one of my forEach statements but I still got the same result. foo = ["bobby", "tommy", "brendan"] foo.forEach((f => { console.log(...

问题:

I noticed that I had a type in one of my forEach statements but I still got the same result.

foo = ["bobby", "tommy", "brendan"]

foo.forEach((f => {
    console.log(f)
}))

vs. 

foo.forEach((f) => {
    console.log(f)
})

I'm curious as to why the result would be the same on the first one, which I made the typo on.


回答1:

An arrow function with one argument can be written in two ways:

f => {
    console.log(f)
}

And

(f) => {
    console.log(f)
}

So the braces around the argument part are optional if there is only one argument.

And placing braces around a complete expression does not change anything for that expression, this:

f => {
    console.log(f)
}

and this

(f => {
    console.log(f)
})

or even this

((f => {
    console.log(f)
}))

is identical.

Your first code block can be formatted as this for a better understanding:

foo.forEach(
   // first argument of forEach
   (f => {
      console.log(f)
   })
   // end of argument list of forEach
)

So there are no misplaced braces, you just removed the optional ones around the f and place optional once around the complete expression.


回答2:

foo.forEach((f => {
    console.log(f)
}))

forEach accepts two paramters(first is method/function and second is optional which value to use as this object when executing callback), wrapping it around with () is not required. Although with arrow functions, if you have a single parameter you don't need to explicity wrap it with (), but you need to wrap you arguments if your method has multiple arguments.

You can check this out for further reading on arrow functions and this for forEach in js

  • 发表于 2018-12-30 00:28
  • 阅读 ( 243 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除