Animal Fun Facts Project | onClick not working with arrow function

https://www.codecademy.com/courses/react-101/projects/js-react-animal-fun-facts

Hi!

I just finished the Animal Fun Facts Project and I notices something weird.

when i declared the displayFact as an arrow function like so -

const displayFact = e => {

const selectedAnimal = e.target.alt;

const animalInfo = animals[selectedAnimal];

const optionIndex = Math.floor(Math.random() * animalInfo.facts.length);

const funFact = animalInfo.facts[optionIndex]

document.getElementById(‘fact’).innerHTML = funFact;

};

clicking on the animal images wouldn’t do anything but when i used function declaration it did seem to work -
function displayFact(e){

const selectedAnimal = e.target.alt;

const animalInfo = animals[selectedAnimal];

const optionIndex = Math.floor(Math.random() * animalInfo.facts.length);

const funFact = animalInfo.facts[optionIndex]

document.getElementById(‘fact’).innerHTML = funFact;

};

any ideas on why that is?

Hello, and welcome to the forums!

Was the function before or after you create the array of images? This matters because of hoisting.

If your code was:

create the images array here
 -- use the displayFact function for onClick on each image

define the displayFact function here

then displayFact wasn’t available to it if you used const or let.

However, when you used function, then it will be hoisted and it was available when you were creating the images array even if the function was defined under it.

3 Likes

Ah, I indeed created the function after the array…
forgot that function expressions and arrow functions don’t get hoisted

Thanks a lot!