The MDN Web Docs explain:
You should avoid using this property in new code, and should instead use the
Eventpassed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code.
I was reviewing my password toggle script yesterday and I found that I had fallen into this trap.
I had the following function…
…That I passed into the
Array.forEach() method at the end of another function:
The problem was that I didn’t explicitly define the
event as a parameter of the
togglePassword() function. This means it was relying on the global
To fix this, I modified the
togglePassword() function to accept the
event as a second argument:
Then I passed in the
If you know me, you’ll know that I like named functions. Therefore, it’s reasonable to ask why I invoked the
togglePassword() function within an anonymous function.
This is because when you use the
forEach() method, you pass in a callback function. The
forEach() method automatically passes specific arguments into your callback function:
- The current element being processed in the array.
- The index of
currentValuein the array.
- The array
forEach()was called upon.
You can name these arguments whatever you like. Therefore, if I did the following, as I did originally…
forEach() method would call the
togglePassword() function with the index of the current element as the second argument.
togglePassword() function has
event defined as its second parameter, it’s just a name. The
forEach() method would pass in the index of the current element.
This would throw a
TypeError, because it would be trying to access the
target property of a number, which doesn’t exist and is therefore
Instead, by using the anonymous function…
…The call to
This is because the
togglePassword() function can access the
event from the lexical scope of the outer
For more information on event delegation and scoping, I recommend the following articles:
- Why event delegation is a better way to listen for events in vanilla JS
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!