when I declared the variable that contains the li outside the for loop, the loop only printed one list item . I read about that issue and found that two identical nodes can’t be present in the same place simultaneously , so the loop deletes the created li every time to add the new one (which results at the end in only one list item)
But on declaring the variable in the for loop , the code worked and 4 list items were created . I want to understand what happened programmatically when I declared the variable inside the loop .
I then tried to print the variable of the list item in the console, and it printed the 4 list items . Does that mean the when the loop runs each time , it just updates the value of the listItem variable to include one more list item at a time ?
But how doesn’t a redeclaration of the variable take place ?
The code :
let theMenu = document.createElement("ul");
for (let i = 0 ; i <= 3; i ) {
let listItem = document.createElement("li");
theMenu.append(listItem);
}
CodePudding user response:
In the code you provided, the listItem variable is declared inside the loop. This means that it is a new variable that is created every time the loop iterates. When the loop iterates, the listItem variable is created, a new li element is created, and then the listItem variable is appended to theMenu. When the loop moves on to the next iteration, the listItem variable is created again and the process repeats.
If you had declared the listItem variable outside the loop, it would only have been created once, and every time the loop tried to append it to theMenu, it would overwrite the previous li element that was appended. This is why only one list item was created when you declared the variable outside the loop.
The reason that the code works when the listItem variable is declared inside the loop is that a new variable is created every time the loop iterates, so there is no overwriting of the previous li element. This allows all four li elements to be created and appended to theMenu.
CodePudding user response:
An element can only appear in a document once.
If you append
an element that is already somewhere in the document then it will be moved not cloned.
If you place the line let listItem = document.createElement("li");
outside the loop then you create one list item, then append it to the document four times (moving it the second and subsequent times).
If you keep that line inside the loop then you create four list items.
CodePudding user response:
Here's what happens during the for...loop iterations on these two cases:
- The listItem is a global variable, therefore the menuItem keeps a single reference to one object.
- The listItem is a local variable, recreated from scratch on each iteration, therefore the menuItem keeps 3 different object references:
Hope the visuals help to understand the concept of variable scoping inside loops.