-2

HTML

<ul id="myList">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

I can't seem to understand how this while statement deletes all the nodes in the above list. Can someone please explain?

JavaScript

while(myList.firstChild) {
    myList.removeChild(myList.firstChild)
};
Community
  • 1
  • 1
Samuel
  • 5,529
  • 5
  • 25
  • 39
  • 1
    It works this way, While loop will execute till `myList` has firstChild. And in the loop you are removing each of its firstChild so the next one becomes the firstchild. It continues until all are removed, when `myList.firstChild` becomes null it is `falsy` so it no longer runs the loop. – PSL Oct 15 '13 at 01:18
  • [The documentation on while](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while) is quite helpful. The loop removes – `removeChild` – the first child – `myList.firstChild` – of a node until there are no more first children (and hence no more children) of the node. – Thomas Upton Oct 15 '13 at 01:18

1 Answers1

5

Read while

enter image description here

HTML

<ul id="myList">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

js code

while(myList.firstChild) // loop will run while myList has a firstChild
    {myList.removeChild(myList.firstChild)
};

Run time

1st time while loop run firstChild is <li>Item 1</li> --> code runs and remove it.

Now HTML

<ul id="myList">
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

Run

2nd time while loop run firstChild is <li>Item 2</li> --> code runs and remove it.

Now HTML

<ul id="myList">
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

Run

3rd time while loop run firstChild is <li>Item 3</li> --> code runs and remove it.

Now HTML

<ul id="myList">
   <li>Item 4</li>
</ul>

Run

4th time while loop run firstChild is <li>Item 4</li> --> code runs and remove it.

Now HTML

<ul id="myList">
</ul>

Run

js code will not run as there is no first child in myList. While loop condition fails.

RobG
  • 142,382
  • 31
  • 172
  • 209
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107