Search code examples
javascriptfor-loopdomjavascript-objectscreateelement

How come there can be 6 different variables inside the for loop in the following javascript code?


I am a beginner in javascript and I have been coding along with a youtube video to create a memory game. The instructor in the video, used the following loop to create 12 different 'img' elements. To give you a little context here, what she has been doing is creating 12(length of the array used in the for loop) image elements and appending them to a parent div element with the class name of 'grid'. So my question is,

In the following code, the loop runs 12 times and since she has typed,

var card = document.createElement('img');

shouldn't the card variable be replaced by the same 'img' element created each time the loop runs? (In other words, isn't it that what is happening here is the card variable been overwritten each time the loop runs?). But at the end, there were 12 cards created as she showed the result. How did this happen?

A screenshot of the code.


Solution

  • At the top of the loop createElement creates an element, so 12 elements are created.

    At the bottom of the loop, the value of card (the element) is read and passed to appendChild.

    It is important to note that it is the value of card that is used and not a reference to the card variable so changing the value of card in the next iteration does not change the element that was appended in the previous loop. JS does not have any features that allow you to reference a variable (only objects).