Peter Olson
Peter Olson

Reputation: 142921

What is this for-loop supposed to do?

I've been trudging through some Javascript code and encountered this loop

for (var w = window; w.window === window.window.window; w = w.window) {
    w.w = w.prompt("Enter password");
    if (w.w === "swordfish") break;
    w.alert("Incorrect password.");
}
w.alert("Welcome, authenticated user!");

This code doesn't really make any sense to me. What in the world is going on here and how does it work?

Upvotes: 1

Views: 146

Answers (3)

Daniel
Daniel

Reputation: 47904

You need to see the preceding line to fully understand this code:

var window = (function () { return this; })();

Upvotes: 1

Well the alertbox keeps popping up for an indefinite period of time unless you provide the password "swordfish" !

If you encounter such script , Just disable JavaScript and view the Source , grab the password (make a note of it) , enable the JS , run the script again and enter the password to see what awaits ;)

Upvotes: 2

Rob W
Rob W

Reputation: 348992

window is always equal to window.window....window, so the loop will never end, unless the password is correct.

A for(;;) loop has the following signature:

for (init; test; increment);

It keeps continuing until test is false. Since window === window is always true, the loop keeps running, until break is encountered. For clarification, w always refers to window.

Upvotes: 7

Related Questions