Animal Fun Facts - Cannot pass arrow function to event handler

I had trouble solving step 11 since the fun facts won’t show up. Changing the arrow function to a normal function solved it finally. However, I still don’t understand why the code below with the displayFact as arrow function won’t work.

Many thanks!

import { animals } from './animals';

import React from 'react';
import ReactDOM from 'react-dom';

const title = '';
const background = <img className='background' alt='ocean' src='/images/ocean.jpg'/>
const images = [];
for (const animal in animals){
  images.push(
    <img 
      key={animal}
      className='animal' 
      alt={animal} 
      src={animals[animal].image} 
      ariaLabel={animal} 
      role='button'
      onClick={displayFact}
    />
  )
};


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

Hi,
that’s a matter of hoisting: An arrow function that is assigned to a const variable isn’t available before it is initialized. You call the function before it is defined here:

This doesn’t matter if declared in the traditional syntax because then it is hoisted:
MDN docs – hoisting

1 Like