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));
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));
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.
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.
key => key.addEventListener('transitionend', removeTransition)
is equivalent to something like
function(key){
return key.addEventListener('transitionend', removeTransition) // binding custom event to event listener
}()