This is a good example of the fact that most of our Javascript code is not executed in the moment is "read" by the browser rather than at some point later in time, usually as a callback triggered by a browser event or user interaction.
The problem here is that each loop interation defines a new function but each function share the same scope. Let's consider scope as the set of variables that are accesible from a piece of code, for example the function body in this case.
Given how Javacript works we are able to use the btnNum
variable that was declared in an outer scope, ie outside the function. The tricky part is that each function points to the same btnNum
variable and when those functions are executed, the btnName
always holds the same value. In this case the value is 3, which is not a valid offset for the array of prizes, so we obtain undefined as a price.
The key here is to remember that functions in Javascript define a new scope and we can treat functions as any other primitive va