-2

I am not understanding below code key => key.addEventListener can you someone please explain this line.

const keys = Array.from(document.querySelectorAll('.key'));
keys.forEach(key => key.addEventListener('transitionend', removeTransition));
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
CodeMan
  • 1,941
  • 6
  • 26
  • 44
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Teemu Jun 20 '17 at 05:05
  • I'm voting to close this question as off-topic because the answer can be found by [reading the fine manual](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – Phil Jun 20 '17 at 05:05

3 Answers3

1

This (keys.forEach(key=>....)) is equivalent to the following:

keys.forEach(function(key){ key.addEventListener('transitionend', removeTransition)});

Comparing the latter with the one with the arrow function expression, key => key.addEventListener('transitionend', removeTransition), I think that the version with the arrow is more succint.

As it is stated here :

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

Shorter syntaxt definitely means more readable code. More readable codes means more easier to catch up with quickly and a sequence more easier to be maintained.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • To expand a bit on this, `=>` is the syntax for [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – JRJurman Jun 20 '17 at 05:05
0

The => is called an arrow function. It's a shorthand method for defining a function.

keys.forEach(function(key){console.log(key)})

can be expressed as an arrow function with

keys.forEach(key => {console.log(key)})

The key is the first parameter passed from forEach, in this case the currentValue. You could expand this if needed to:

keys.forEach((currentValue, index, array) => {...})

if you needed access to the other parameters available in forEach.

For more details on Arrow Functions see the MDN Documentation.

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
0
key => key.addEventListener('transitionend', removeTransition) 

is equivalent to something like

function(key){
return key.addEventListener('transitionend', removeTransition) // binding custom event to event listener
}()
Nofi
  • 2,107
  • 1
  • 15
  • 23