-1

Below is a snippet of code from codecademy. I'm new to Javascript and React so I just want to ask why parentheses isn't needed after this.myFunc. I thought invoking a function in Javascript requires parentheses. Is this React specific, or am I missing something here?

Thanks!

class MyClass extends React.Component {
  myFunc() {
    alert('Stop it.  Stop hovering.');
  }
  render() {
    return (
      <div onHover={this.myFunc}>
      </div>
    );
  }
}
apes
  • 11
  • 1
    Invoking the function does require parentheses, but you don't want the function to execute until a hover event happens. – takendarkk Dec 28 '18 at 17:48
  • Possible duplicate of [Difference between (function(){})(); and function(){}();](https://stackoverflow.com/questions/423228/difference-between-function-and-function) – Bharath Kumar S Dec 28 '18 at 17:53
  • this sums it up pretty nicely... https://stackoverflow.com/questions/20485425/why-in-javascript-event-handler-functions-with-parentheses – Noman Hassan Dec 28 '18 at 17:57

3 Answers3

1

If a function is written with parentheses, it will be called on render whereas a function without parentheses is simply a reference to that function and will not self-invoke but wait for the hover event to happen.

<div onHover={this.myFunc()}> // Calls the myFunc function and invokes it on render

<div onHover={this.myFunc}> // References the myFunc function and invokes it on hover
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
0

React will handle calling that function for you when the user hovers. In this case if you change it to <div onHover={this.myFunc()}> The function will be run on render, and if that function returns a function, the function that gets returned will be run on hover. Which is not what you want.

This can be a useful feature of JavaScript to give another section of code a function to run later.

For example:

setTimeout(myFunc, 1000);

function myFunc() {
    console.log("1 second has passed");
}

I don't want myFunc to be run instantly. Only after the timeout has completed. So I let the setTimeout call it for me.

Charlie Fish
  • 18,491
  • 19
  • 86
  • 179
0

When you invoke function you will set onHover to return value of that function which is undefined in this case because your function returns nothing. You want to bind onHover event to function itself not it's return value.

Akın Tekeoğlu
  • 161
  • 2
  • 11