I’m working on the animal facts project https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-22-react-part-i/modules/wdcp-22-jsx/projects/js-react-animal-fun-facts and have run in to an unexpected problem. the instructions for step 9 are:
- Create a function
displayFact()
that takes one parametere
, the event. We want this function to pick a random fun fact based on the selected animal. - Inside of the function, use
e.target.alt
to get the name of the animal being clicked. - Generate a random index and use it to access an element in the animal’s
.facts
array. - Save the fun fact in a variable.
Nothing weird, but it doesn’t work if i write the fuction as an arrow function, why?
This works:
function displayFact(e) {
const selectedAnimal = e.target.alt;
const animalInfo = animals[selectedAnimal]
const randomIndex = Math.floor(Math.random() * animalInfo.facts.length);
const funFact = animalInfo.facts[randomIndex];
document.getElementById('fact').innerHTML = funFact;
};
But this doesn’t:
const displayFact = e => {
const selectedAnimal = e.target.alt;
const animalInfo = animals[selectedAnimal]
const randomIndex = Math.floor(Math.random() * animalInfo.facts.length);
const funFact = animalInfo.facts[randomIndex];
document.getElementById('fact').innerHTML = funFact;
};
Why? The only difference is on the first line.
Here is the full code for the exercise with both ones commented out if you want to test it