ES6 Arrow Functions () vs _

Viewed 141

I tried looking this up and did not find an answer. Is there any reason to use _ over () when passing in 0 parameters in an arrow function? Just asking out of curiosity.

// ...(() => {}) vs (_ => {})
1 Answers

The differences are:

  • _ creates an identifier for the _ variable. (In rare circumstances, this may be confusing if one is using a library which assigns to window._, like underscore.js)
  • Using _ means that parentheses aren't needed. (In contrast, declaring a function with zero arguments requires an empty parameter list with ()) Some like saving on a character by using _ instead.

(One could have, equivalently, used any other argument name like z which then goes unused - but the convention for an unused variable is to use _)

If one isn't using a library that assigns to window._, then the _ parameter won't shadow it, so both options work just fine. Feel free to choose whichever strikes your fancy.

Note that a common linting rule forbids the declaration of unused parameters, and will require () instead of _.

Related