Hi there @impresently!
When a function is run as a direct result of an event firing, due to an event listener being added to the object on which the event fires, the function implicitly has an event object available inside its lexical scope (i.e. inside the function, but not outside it). The reason we write
event, or in this case
clickedImage as a parameter is to give a definition to this event object — i.e. a name we can refer to it as.
So in this case, each time the loop is run, the
displayThumb() function is defined, and we add an event listener to the
newImage created on each round of the loop that makes it so that
displayThumb() is run when the image in question is clicked on.
So the event object passed into the function each time an image is clicked (
clickedImage in your case) varies depending on which image was clicked. It contains information relevant to the image that was clicked.
target attribute contains a reference to the
image itself — “the target of the event”. This is why when you do
clickedImage.target, you can directly access the properties available on image. We can therefore use
getAttribute('src') to access the contents of the image’s
src attribute (the path to the image), etc.
Now, we also need to talk about the order in which things are run around loops. When you run a loop and it has a function inside it, the different loop iterations all run first, then the functions inside the loop iterations will run afterwards.
This is why the second code example DOESN’T work properly. By the time the loop iterations have all run,
src value is equal to the path to the last image. The event listeners are all set up correctly, but the function will always set the main image displayed to that last image.
If you instead get the
e.target.getAttribute(), the value will be relative to the image clicked on, not the value of
newImage after the loops have all run, which is always equal to the last image.
Does that help? Happy to discuss some more if you are still not clear.