简体   繁体   中英

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(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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM