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