1

The context here is I am looking at a React.js application, and I see:

const _onClick = _ => setClick(!clicked);

If I understand it correctly, this is shorthand for something like:

const _onClick = () => { setClick(!clicked); } 

Or, pre-ES6:

var _onClick = function() {
    setClick(!clicked);
}

But I've never seen an arrow function without parentheses. Is the underscore a function name?

Vee
  • 729
  • 10
  • 27
  • 1
    `_` is a variable name, like `a`, `b` or `myVariable`. You could write `const _onClick = a => setClick(!clicked);`. In this case `a` (or `_`) is unused, some prefer writing `= a => ` than `= () =>` (function that takes no parameter). – Jeremy Thille Jul 10 '21 at 19:48

1 Answers1

2

The underscore is a naming convention for an unused function parameter, but it's being used there so that the function can be written without parentheses. Arrow functions with a single parameter don't need the parentheses around it.

Ace
  • 1,028
  • 2
  • 10
  • 22
  • 1
    Javascript doesn't care, but Typescript would complain : The parameter is declared but never used! You are calling the function without passing it anything but it requires a parameter! Etc. The application wouldn't compile. – Jeremy Thille Jul 10 '21 at 19:49
  • @JeremyThille this is correct, but perhaps irrelevant to the question? – Ace Jul 10 '21 at 19:51
  • Just a sidenote. `= _ =>` is accepted by Javascript when it shouldn't (Javascript is too loose). For this reason, IMO the correct syntax is `= () =>` (no parameter required) – Jeremy Thille Jul 10 '21 at 19:53