DEV Community

Discussion on: Arrow Function vs Function

Collapse
sshymko profile image
Sergii Shymko Author • Edited

Arrow functions cannot be called with a dynamic this scope useful to reuse the same callback on different elements.

For example:

let button1 = document.getElementById('button1');
let button2 = document.getElementById('button2');

let callback = function() {
  console.log(`Button ${this.id} clicked.`);
};

button1.onclick = callback;
button2.onclick = callback;
Enter fullscreen mode Exit fullscreen mode

It will log button1 and button2 respectively. Such behavior cannot be reproduced by a single arrow function. You'd have to declare two arrow functions each enclosing the context of the respective element.

Collapse
piyush1104 profile image
Piyush Bansal

Can't we just get this info from 'event.target'?

Thread Thread
sshymko profile image
Sergii Shymko Author

Good point. That's true for DOM events, but not in general case of arbitrary callback.