javascriptfor-loopscopes

The for loop works on declaring the variable inside it but not in the global scope


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);
} 

Solution

  • Here's what happens during the for...loop iterations on these two cases:

    1. The listItem is a global variable, therefore the menuItem keeps a single reference to one object.

    enter image description here

    1. The listItem is a local variable, recreated from scratch on each iteration, therefore the menuItem keeps 3 different object references:

    enter image description here

    Hope the visuals (created with whimsical) help to understand the concept of variable scoping inside loops.