Works with function declaration but not with arrow funtion

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:

  1. Create a function displayFact() that takes one parameter e, the event. We want this function to pick a random fun fact based on the selected animal.
  2. Inside of the function, use e.target.alt to get the name of the animal being clicked.
  3. Generate a random index and use it to access an element in the animal’s .facts array.
  4. 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

Hi,
the link to your full code isn’t working, so I can only assume that it is a hoisting issue.
That means that function declarations and variables declared with var are available all over the scope, wherever you defined them. Variables declared with const and let are not hoisted – and therefore only available below the line where you defined them. Move the fat arrow function up – above the function call – and it’ll probably work.

2 Likes

Thank you.
Yes, moving the arrow function up to before it was called worked. I thought functions worked the same no matter how they were declared. My thought was that maybe there was something weird with React and arrow functions, had completely forgotten about hoisting (other than that functions still work when declared after they are called and that some people dislike that about javascript).

1 Like