Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

JAVASCRIPT WINDOW AND DOCUMENT

https://teamtreehouse.com/library/thinking-globally <-- here mr guil says that all global variables belong to a global object called window in browsers but mdn says "the Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window. A window for a given document can be obtained using the document.defaultView property.

A global variable, window, representing the window in which the script is running, is exposed to JavaScript code."

how do all global variables belong in the global object window when window is a global variable?

1 Answer

Wiktor Bednarz
Wiktor Bednarz
18,647 Points

Every JavaScript code needs to live in some scope. It could be a browser, a command terminal or some other interpreter. You could call this a 'main container'. In case of a website, you are rendering it with your browser. Each time you load in a website, the browser only loads the one current site you requested. So when you go to https://www.google.com, google loads you a single site, which is the root of their service - you don't get other sites along with it, for example site containing a random search results. You only get this one site.

So whenever you load a site within a wider environment, the browser creates a window object representing it. Window object for each site is unique. And even though it's basically a variable - this particular window object you receive is becoming the scope for JavaScript code attached to the site.

So to picture it out for you - let's assume we've got some website living on a domain 'http:\www.mygloriouswebsite.com' and on that website you've got your homepage, contact page, and some about page. Whenever you visit each one of those pages, the browser creates a new window object. Within this object, it executes all the scripts attached to it. And even though you may have one script file attached to every site on your website, the browser executes it from scratch on each visit to the site.

ti;dr - Even though window object could be considered a variable itself, for a browser it defines the scope of execution for the code attached to it.

I hope this answers your question,

Wiktor Bednarz

thank you for explaining