- Closure: In the code snippet you sent below the approach is clear but you have run into something called
Closure
. What you are attempting to do here is to create a different environment for each onclick
event so that we alert()
a different message, however, because of the created closure
we are actually telling our 3 buttons to share the parent environment. This means that by the time any of our buttons are clicked the loop has completed reaches an index of 3 which is undefined
in our array of strings since arrays are zero indexed in javascript.
You should research a little about Closures
and see if you can identify how to create a unique environment for each button.
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>