What is a global variable in JavaScript?

advertisements

I'm from a C# Class(), fields, properties, namespace...world. And I just launched myself into javascript. So far I've been doing great. However one of my friends was looking at my code and asked me why I did this.

function Position (x, y) {
    this.X = x;
    this.Y = y;
}

friend: "You've just over-rided Position..." me : "What Position?" friend: "Could be anything the browser is using." me : "I am only running this script - it works perfectly" friend: "Until it doesn't work."

Ok so... What? Turns out Position is Global .. but where and to what extent? My friend makes it sound like its Global to the entire browser. So my question is;

Is a javascript Global, Global to the Entire Browser? > The Window Only? > The Tab Only?? > how far does it go??


When JavaScript is running in a browser, a global variable is a property of the window object. Therefore, it is global to the current window only, not to other browser windows, tabs, frames, or iframes. Each one of those has its own window object.

There is no Position global built into JavaScript. Your friend's concern is probably that some other piece of code you include on your page may also define that same global. So one of those definitions (whichever is defined later) will overwrite the other.