May 11, 2000 - Checking for a Window's Existence | WebReference

May 11, 2000 - Checking for a Window's Existence

Yehuda Shiran May 11, 2000
Checking for a Window's Existence
Tips: May 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

So you know the browser actually created the new window. But does it still exist? Not necessarily. You need to make sure the window variable holds a real window object. Since every window object features an open() method, you can detect the method via object detection:

// if win.open exists, move the window
if (win.open) win.moveTo(0, 0);

The variable win reflects the window object of the window, so win.open references the window's window.open() method. Notice that the conditional expression is a function reference (without parentheses), not a function call. You shouldn't attempt to evaluate win.open unless you know for sure that win exists. The following statement demonstrates the correct implementation:

// if win and win.open exist, move the window
if (win && win.open) win.moveTo(0, 0);

Since && is a short-circuit operator, it only evaluates its second operand (win.open, in this case) if the first one (win) reflects a true value. If the first operand evaluates to false, the entire expression is obviously false, so JavaScript doesn't even look at the second operand. This is an important behavior, because the expression win.open generates an error if win doesn't exist.