[javascript] Javascript: 'window' is not defined

I'm trying to learn JavaScript, but the following code has been giving me a lot of trouble:

window.onload = function () {
    for ( var i = 0; i < seats.length; i++) {
        for ( var j = 0; j < seats.length; j++) {
            document.getElementById(getSeatId(i, j)).onclick = function(evt) {
                getSeatStatus(getSeatId(i, j));
            };
        }
    }
    document.getElementById("search").onclick = findSeat;
    document.getElementById("male_search").onclick = findMaleSeats;
    initSeats();
};

It is from an external JS file and it is the only file linked to the page. findSeat, findMaleSeats, getSeatId, and initSeats are all defined a little bit later in the file. When I double click this file, I get the following error:

Windows Script Host
Error: 'window' is not defined
Code: 800A1391

I already tried moving the code to other places in the file, assigning a different function (even an empty function) to window.onload and many other things. It just seems that my computer doesn't know what window is. And if I try to open the HTML in a browser the nothing loads (as one would expect).

Does someone know what is wrong with this?

This question is related to javascript dom

The answer is


The window object represents an open window in a browser. Since you are not running your code within a browser, but via Windows Script Host, the interpreter won't be able to find the window object, since it does not exist, since you're not within a web browser.


Trying to access an undefined variable will throw you a ReferenceError.

A solution to this is to use typeof:

if (typeof window === "undefined") {
  console.log("Oops, `window` is not defined")
}

or a try catch:

try { window } catch (err) {
  console.log("Oops, `window` is not defined")
}

While typeof window is probably the cleanest of the two, the try catch can still be useful in some cases.