-1

How come the below code is not printing in the console. If I use a normal function it works.

document.addEventListener('DOMContentLoaded', recipeController);

const recipeController = () => console.log("hello");
Nipun Thennakoon
  • 3,586
  • 1
  • 18
  • 26
soulsako20
  • 231
  • 3
  • 10
  • @Taplar — The problem doesn't really have anything much to do with arrow functions, and certainly nothing to do with the `this` keyword – Quentin Jul 02 '18 at 15:36
  • Ah, I misread the question. Thought it was an arrow function issue, rather than a hoisting issue. – Taplar Jul 02 '18 at 15:38
  • 1
    Possible duplicate of [Are variables declared with let or const not hoisted in ES6?](https://stackoverflow.com/questions/31219420/are-variables-declared-with-let-or-const-not-hoisted-in-es6) – Heretic Monkey Jul 02 '18 at 16:52

2 Answers2

2

const variables must be declared before they are used. They are not hoisted.

zfrisch
  • 8,474
  • 1
  • 22
  • 34
2

Functions are forward-referencing (hoisted), what you have here is a variable declaration (non-hoisted). In this case, you need to declare your recipeController above your event listener.

const recipeController = () => console.log("hello");
document.addEventListener('DOMContentLoaded', recipeController);
KevBot
  • 17,900
  • 5
  • 50
  • 68