Function without argument : () or _

i got question for you.

When you create a function without argument you used to do

const function myFunction = () => {
...
}

but recently i found we could do the same thing with ‘_’

const function myFunction = _ => {
...
}

so, my question is, what’s the difference?

Is it being wrong to use ‘_’ just ’cause everyone use ‘()’ ?

Answer

() is a list of zero parameters.

(_) is a list of one parameter (named _)

_ is a shorthand for (_) because the parentheses are optional when there is exactly one parameter.


“Wrong” is subjective, but:

  • if a function doesn’t use any parameters then providing a variable to assign them to doesn’t make sense (not even if it has a name which tells you nothing about what it is for).
  • writing non-idiomatic code imposes barriers for people who have to come along and maintain your code later.

Aside: You have a syntax error. You can’t combine the function keyword with an arrow function.

Leave a Reply

Your email address will not be published. Required fields are marked *