It is commonly frowned upon to automatically create global variables because it can lead to confusion in the codebase, making it difficult to determine if a variable was intentionally set as global or if it was an oversight. The automatic creation of global variables does not function in ES5 strict mode and may be phased out in future ECMAScript releases.
In JavaScript within a browser, the global scope is represented by window
. When referencing document
, you are essentially referring to window.document
. The recommended practice for defining global variables in a browser environment is to add them directly to window
(or global
in Node.js). Here's an example from jQuery:
window.jQuery = window.$ = jQuery;
Some properties on window
(and thus global variables) are read-only and cannot be overwritten. For instance, window.document
is read-only (as tested in Chrome):
window.document; // → Document
window.document = 'foo'; // → "foo" // It worked!
window.document; // → Document // Hmm, no it didn’t
Interestingly, most browsers create properties on window
(creating global variables) for each id in the document. Although many browsers allow these values to be changed, Internet Explorer enforces read-only status.
This showcases another reason why global variables in JavaScript can pose risks—there is a potential for your ids to conflict with read-only window
properties either presently or in future browser versions.
At the top level (outside of a function), var
defines global variables. Declaring var document = 'foo'
at the top level will not throw an error, but document
would still reference Document
, not "foo"
.
As a side note, modern browsers supporting ES5 enable the creation of read-only globals using Object.defineProperty
:
Object.defineProperty(window, 'foo', { value: 'bar', writable: false });
foo = 'baz';
foo; // → "bar"
I offer three suggestions for you to consider:
Continue utilizing global variables for your elements while ensuring they are only created on window
if they do not already exist, thereby maintaining clarity and compatibility with ES5:
if ( ! window.randomDiv) {
window.randomDiv = document.getElementById('randomDiv');
}
Establish an object on window
to serve as your application's namespace, preventing conflicts with other libraries or browser components. This approach is widely accepted and beneficial, particularly when needing cross-file accessibility:
// At the beginning of your code…
window.Fantabulum = {};
// Later on…
Fantabulum.randomDiv = document.getElementById("randomDiv");
Avoid reliance on global variables. Ensure that your application's logic is encapsulated within a function (which should already be the case to prevent leakage of variables) and declare element-specific variables within it:
(function(){
var randomDiv = document.getElementById("randomDiv");
})();