Animal Facts Project (Arrow Functions)

Hey

I’m working on the animal facts project as part of the React course.

I created an image with an ‘onClick’ attribute of {displayFact}, which calls the following function:

function displayFact(e) {
const animalName = e.target.alt;
const index = Math.floor(Math.random() * animals[animalName].facts.length);
const funFact = animals[animalName].facts[index];
const p = document.getElementById(“fact”);
p.innerHTML = funFact;
}

This works fine and the program works as intended. HOWEVER, I originally coded this using arrow function notation, and the function did not work.

My original code was:

const displayFact = e => {
const animalName = e.target.alt;
const index = Math.floor(Math.random() * animals[animalName].facts.length);
const funFact = animals[animalName].facts[index];
const p = document.getElementById(“fact”);
p.innerHTML = funFact;
}

Is there any reason that we can’t use a function expression with arrow notation here? I can’t work out why we need to specifically use the ‘function’ declaration’, rather than arrow notation.

Luke

To preserve code formatting in forum posts, see: How do I format code in my posts?

As for the arrow function, see this post:

1 Like

Thanks so much, this was the answer! I feel like I learned this in an earlier lesson so was just me being forgetful it seems…

Noted re formatting my code for posts, thanks v much!

1 Like

Thank you for this, it was driving me crazy.