1

I'm using d3.js for an application, and in D3 (v7.6), event handlers get passed the event object and the data associated with the node receiving the event. I have some event handlers that don't actually use the event object but just need access to its data. For example:

selection.on('click', (event, d) => {
   console.log(d)
})

In the above case, the handler doesn't need event. However, as far as I know, I still need to include event as the first argument passed to the function in order to access d. If I changed the function to d => console.log(d), d will actually be the event object and not the data I need.

I'm wondering what is considered best practice in this situation, where there's a function that only needs the second argument passed to it and not the first. Do I just keep event as the first argument, even though it won't be used? Or is there a better approach to this?

Eric
  • 1,167
  • 3
  • 11
  • 18
  • Typically use `_event` in my experience. This plays well with the eslint [argsIgnorePattern](https://eslint.org/docs/latest/rules/no-unused-vars#argsignorepattern), for example. – jarmod Sep 08 '22 at 17:38
  • @jarmod Isn't the underscore in front of a variable name also meant to indicate in JS that the variable is private? – Eric Sep 08 '22 at 21:14
  • Yes, in practice it's a common convention for that too. Typically though, there shouldn't be much ambiguity between which of the two questionable practices a given scenario is. – jarmod Sep 08 '22 at 22:12
  • 1
    In my opinion `_event` would tell me that the variable is private, which is not the case here. What I do is `(_, d) =>`, which normally indicates that the argument is not used at all. Since this is a matter of convention, instead of closing as a duplicate I'll just link this Q/A here: https://stackoverflow.com/q/27637013/5768908 – Gerardo Furtado Sep 08 '22 at 23:15
  • 1
    @GerardoFurtado in the example shown, it's not clear why it would appear to be private. It's not a class property, it's the parameter to a function, and its scope is limited to the function. Agree that `_` is also commonly used (nice, another convention!) but the downside to that, imo, is that you lose information, specifically in this case that the thing you are not using is an event (which I personally find helpful to know). But agree that `_` is also a common convention. – jarmod Sep 09 '22 at 01:08
  • I appreciate the different perspectives presented here. @GerardoFurtado Thanks for the reference to the other question, which also points out that the use of the standalone underscore as a parameter can also get confusing when a project also uses libraries like lodash. It seems that with either convention (`_event` or `_`) there are drawbacks, and one may be more suitable than the other depending on the project. – Eric Sep 12 '22 at 16:51

0 Answers0