Why do I get errors when I pass the method with () to the attribute?

Question

Why do I get errors when I pass the method with () to the attribute?

Answer

Let’s take this exercise, we have a changeName method:

changeName(newName){
  this.setState({
    name: newName
  });
}

and we also have a Child component that we are passing this method to:

render() {
    return <Child name={this.state.name} onChange= { this.changeName() }/>
  }
// pay close attention  we  have () on the method  _______________^^^^

We may remember that with functions and methods from objects, having parenthesis means that we are calling them, the same principle applies here, as we pass the method as a property with the parenthesis we are calling it, so when the program gets to the render method and sees the () it will trigger that method instead of just passing it to the Child component under the onChange attribute, causing the syntax error, now, this error is from Codecademy, but when dealing with this in real life, two things may happen, either the method is triggered (since it is possible to call a method that way, but not commonly recommended) or like in this case newName would be undefined, bringing a different error. In Short, always, when passing a method to be used in another component we don’t want to call it at all:

render() {
    return <Child name={this.state.name} onChange={this.changeName}/>
  }

That way we are able to call it under the atribute name, from inside the Child component.

9 Likes

A simple way to explain this would be that

  1. passing this.changeName() (or any function with ()) will return the evaluated function aka the result. Passing it this way will call the function and return the value.
  2. Passing this.changeName (or any function without ()) will return the reference to the function. What’s the reference to the function? Simply one can think of it as the address in memory of the function.

So, think about it like passing a note with the address of where the function is, instead of running the function and THEN passing the value of the evaluated function.

Hope this helps.

50 Likes

finally, someone that speaks sense

thanks, nice explanation :+1:

1 Like

:clap: Good answer!!!

The analogy you provided really helps to reinforce the idea from a different perspective. It’s the icing on the cake.

Speaking of analogies here’s this little gem of a website I found during my early web development journey: CodeAnalogies: Web development lessons that use analogies to make new concepts simple

6 Likes

Love it!! Thanks for this gem.