JavaScript Succinctly by Cody Lindley is a concise, yet thorough examination of JavaScript objects and their supporting nuances, such as primitive values, scope, inheritance, the head object, and more. It is intended for intermerdiate JavaScript developers looking to solidify their understanding of the language, and those who have only worked with JavaScript under the mantle of libraries (such as jQuery, Prototype, etc.). The following excerpt discusses managing the scope of variables and properties. This book can be downloaded for free from Syncfusion's Technology Resource Portal. To download the ebook go here: http://www.syncfusion.com/resources/techportal/ebooks/javascript?utm_medium=BizDev-CodeMag0813

Conceptual overview of the head object

JavaScript code itself must be contained within an object. For example, when crafting JavaScript code for a web browser environment, JavaScript is contained and executed within the window object. This window object is considered to be the "head object," or sometimes confusingly referred to as "the global object." All implementations of JavaScript require the use of a single head object.

The head object is set up by JavaScript behind the scenes to encapsulate user-defined code and to house the native code with which JavaScript comes prepackaged. User-defined code is placed by JavaScript inside the head object for execution. Let's verify this as it pertains to a web browser.

In the following sample, I am creating some JavaScript values and verifying the values are placed in the head window object.

Sample: sample64.html

<!DOCTYPE html><html lang="en"><body><script>
    
    var myStringVar = 'myString';
    var myFunctionVar = function () { };
    myString = 'myString';
    myFunction = function () { };
    
    console.log('myStringVar' in window); // Returns true.
    console.log('myFunctionVar' in window); // Returns true.
    console.log('myString' in window); // Returns true.
    console.log('myFunction' in window); // Return true.
    
</script></body></html>

You should always be aware that when you write JavaScript, it will be written in the context of the head object. The remaining material in this chapter assumes you are aware that the term "head object" is synonymous with "global object."

Notes

The head object is the highest scope/context available in a JavaScript environment.

Global functions contained within the head object

JavaScript ships with some predefined functions. The following native functions are considered methods of the head object (e.g., in a web browser, window.parseInt('500')). You can think of these as ready-to-use functions and methods (of the head object) provided by JavaScript.

  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • eval()
  • isFinite()
  • isNaN()
  • parseFloat()
  • parseInt()

The head object vs. global properties and global variables

Do not confuse the head object with global properties or global variables contained within the global scope. The head object is an object that contains all objects. The term "global properties" or "global variables" is used to refer to values directly contained inside the head object and are not specifically scoped to other objects. These values are considered global because no matter where code is currently executing, in terms of scope, all code has access (via the scope chain) to these global properties and variables.

In the following sample, I place a fooproperty in the global scope, then access this property from a different scope.

Sample: sample65.html

<!DOCTYPE html><html lang="en"><body><script>
    
    var foo = 'bar'; // foo is a global object and a property of the head/window object.
    
    var myApp = function () { // Remember functions create scope.
        var run = function () {
            // Logs bar, foo's value is found via the scope chain in the head object.
            console.log(foo);
        } ();
    }
    
    myApp();
    
</script></body></html>

Had I placed the foo property outside of the global scope, the console.log function would return undefined. This is demonstrated in the next code example.

Sample: sample66.html

<!DOCTYPE html><html lang="en"><body><script>
    
    var myFunction = function () { var foo = 'bar' }; // foo is now in the scope of myFunction()
    
    var myApp = function () {
        var run = function () {
            console.log(foo); // foo is undefined, no longer in the global scope, an error occurs.
        } ();
    }
    
    myApp();
    
</script></body></html>

In the browser environment, this is why global property methods (e.g., window.alert()) can be invoked from any scope. What you need to take away from this is that anything in the global scope is available to any scope, and thus gets the title of "global variable" or "global property.”

Notes

There is a slight difference between using var and not using var in the global scope (global properties vs. global variables). Have a look at this Stack Overflow exchange for the details: Difference between using var and not using var in JavaScript.

Referring to the head object

There are typically two ways to reference the head object. The first way is to simply reference the name given to the head object (e.g., in a web browser this would be window). The second way is to use the this keyword in the global scope. Each of these is detailed in the following sample.

Sample: sample67.html

<!DOCTYPE html><html lang="en"><body><script>
    
    var foo = 'bar';
    
    windowRef1 = window;
    windowRef2 = this;
    
    console.log(windowRef1, windowRef2); // Logs reference to window object.
    
    console.log(windowRef1.foo, windowRef2.foo); // Logs 'bar', 'bar'.
    
</script></body></html>

In this example, we explicitly store a reference to the head object in two variables that are then used to gain access to the global foo variable.

The head object is implied and typically not referenced explicitly

Typically a reference to the head object is not used because it is implied. For example, in the browser environment window.alert and alert() are essentially the same statement. JavaScript fills in the blanks here. Because the window object (i.e. the head object) is the last object checked in the scope chain for a value, the window object is essentially always implied. In the next example, we leverage the alert() function which is contained in the global scope.

Sample: sample68.html

<!DOCTYPE html><html lang="en"><body><script>
    
    var foo = { // window is implied here, window.foo
        fooMethod: function () {
            alert('foo' + 'bar'); // window is implied here, window.alert
            window.alert('foo' + 'bar'); // window is explicitly used, with the same effect.
        }
    }
    
    foo.fooMethod(); // window is implied here, window.foo.fooMethod()
    
</script></body></html>

Make sure you understand that the head object is implied even when you don't explicitly include it, because the head object is the last stop in the scope chain.

Notes

Being explicit (e.g., window.alert() vs. alert()) costs a little bit more with regard to performance (how fast the code runs). It's faster if you rely on the scope chain alone and avoid explicitly referencing the head object even if you know the property you want is contained in the global scope.