Arrow function in eventListener issue

link - (https://codepen.io/kamaljyotwal/pen/yLOYpdr?editors=0110)

Normal function is changing the background color on click, and the anonymous arrow function is also working in event listener.

But when i do same with named arrow function in callback it not working. why?

please shed some light.
uncomment code to test.

Hello there,

A named arrow function like this works the same as any other variable - you cannot use it, before you define it:

var red = () => {
  document.body.style.backgroundColor = "red";
};

Try defining it, before the function call…

1 Like

It’s not defined, you need to define it before you use it

hey, if the issue is that it is defined on the next line then, why is normal function working even if defined later.

because i was thinking to add functions after eventListener as it will get
big soon after adding stuff.
Thanks

These are different in that:

  1. The function keyword is read by the compiler upon first reading. All functions are then taken into memory as being defined. This all happens before the code is run.
  2. Using the const red = () => ... syntax, does not define a function. This is a variable named red with a value of some-anonymous-function.

It is important to realise, whilst you can use this new syntax very similarly to how you would a function, the introduction of this syntax was not to replace explicit functions. Arrow functions are purely useful for their short-handedness. They are basically JavaScript’s lambda functions.

So, if you want to write a globally-scoped function, and keep your script neat by placing it at the end, use the function keyword.
If you want to save some space (normally, when writing callbacks), use the arrow function syntax.

Hope this helps

Now i understand , nice explanation
Thank you for your prompt response and your time for replying to this thread.