var f = 5, d;
while (f === 5) d = 2;
alert(d);
Why does this freeze my page. I thought only when the page is doing a document.write, alert, or console.log inside a while loop (without a incremented value with a limit) it will freeze the page, but not with variables… Do I still have to have a var i = 0; while (i < 5 &&... just to get this to work?
EDIT: I found this in the source-code of google. This while loop doesn’t have a number limit but it doesn’t freeze the page:
while (a && !(a.getAttribute && (b = a.getAttribute("eid")))) a = a.parentNode;
The Google loop you edited into your question is testing the value of
ain the while condition and it is modifying the value ofainside the loop, so the loop will terminate whena(or one of the other conditions based ona) is no longer truthy.For a loop to terminate, some value that you are testing in the loop condition must change to a falsey value sometime during the iteration of the loop. It doesn’t have to be numbers, it can be other things that have a truthy or falsey notion to them.
In that Google loop, there are two conditions that can make it terminate:
ais no longer truthy (null, undefined, 0, false, etc…).So, basically this is going up the parent chain looking for the first parent that has getAttribute(“eid”). It stops either when it runs out of parents to check or it finds a parent with that attribute.