Arrow syntax functions in React

This question is dealing with a step for the Animal Fun Facts project. (https://www.codecademy.com/courses/react-101/projects/js-react-animal-fun-facts) Specifically, for step 9, we must create a event handler function - {displayFact(e)} I originally defined this function with JS arrow syntax. The program failed to work, the fix was to convert to standard function syntax. Why is this the case? When are you allowed to use the arrow syntax in React?

In the below code snippet, the version of displayFact that is uncommented works, however the version that is commented our fails. Would appreciate an explanation!

What was the error thrown? Have you tried replicating the error locally?

I don’t think the service allows us to see what errors were thrown…
I’m not sure how to get any debug info from the codeacademy terminal.

I haven’t tried replicating this locally…but that does sound like a good suggestion. Will look into

You can open the browser’s console. It shows the errors thrown by the animal funfact project. Works for all other projects that don’t have their own console in the sandbox as well. Generally it makes sense to develop the react projects locally, the devtools provided by the default installation (npx create-react-app myfirstreactapp) are much more helpful and I preferred that for the more complex projects.

Hmm, using the console to debug, I still cannot determine why the arrow function syntax doesn’t work…the function never runs at all.

I tried replacing the onClick callback with an anonymous arrow function ( (e) => console.log(e) ) and this worked, but when the onClick callback is set to a function defined with arrow syntax, it still will not work.

Arrow functions (if they are defined with const or let keyword) don’t do hoisting. That means when defined after they are called, they aren’t available. In your screenshot you defined the arrow function below the displayFact function that calls the arrow function. You should have got an error then like Reference error: xy undefined…

Thanks for this context.

So functions defined like this:

function functionName(e) {
     // code
};

can be defined anywhere? They don’t have to be defined before they are called? If this is the case, why not always write functions in this manner? It may be visually less appealing than the arrow function at times, but it seems to me it would be safer to use the traditional syntax and not have to worry about bugs like this one…

EDIT: well its not a bug I suppose, but it still seems easier to use the traditional syntax and not have to worry about it

Yes. I can’t give you a well-founded analysis which is better or safer. I learnt Javascript with the ES6 syntax and can’t compare. There are some downsides to using hoisting as well as there are differences with the context of this keyword. Maybe @toastedpitabread has better informations on this.