onClick is an attribute that takes a function - under the hood, React, when receiving <some-element onClick={someFunction}/>, saves someFunction for later (notice that it doesn't call the function), and then calls the function when the user clicks. Note that you can rewrite this as <some-element onClick={(...args) => someFunction(...args)}/>, if that makes more sense to you.
Now here's what happens when the user presses on an element where onKeyPress={e => e.key === 'Enter' && this.validate()} is present:
- The function
e => e.key === 'Enter' && this.validate() is called
e.key === 'Enter' && this.validate() is evaluated
e.key === 'Enter' is evaluated. If it evaluates to true, then:
this.validate() is called and evaluated as a boolean
Notice how it is slighly different than when onKeyPress={e => e.key === 'Enter' && this.validate} is written instead:
- The function
e => e.key === 'Enter' && this.validate is called
e.key === 'Enter' && this.validate is evaluated
e.key === 'Enter' is evaluated. If it evaluates to true, then:
this.validate is evaluated as a boolean. If the function exists, it is coerced into the boolean true, else this.validate evaluates to undefined, which is coerced into the boolean false. Notice how this.validate did not get called. I'd regard this as a bug, except if you expressively want this behavior to happen.
this.validateis a function that is not being immediately invoked or called. It's being stored for later. The code says "when clicked, I want you to callthis.validate". In the example on line 2, that's a totally different context. There, you actually want to call it because its return value is being evaluated as part of a boolean expression rather than stored for later use. Line three says, "is the key equal to "Enter" and is this function definition truthy?" which doesn't make sense here (although you may want to ask whether a function var is defined, i.e. truthy).