Feb 24, 2008

Primitive Types and Reference Types

Numbers, boolean values, and the null and undefined types are primitive. Objects, arrays, and functions are reference types.

            var a = 3.14;  // Declare and initialize a variable

            var b = a;     // Copy the variable's value to a new variable

            a = 4;         // Modify the value of the original variable

            alert(b)       // Displays 3.14; the copy has not changed

            var a = [1,2,3];  // Initialize a variable to refer to an array

            var b = a;        // Copy that reference into a new variable

            a[0] = 99;        // Modify the array using the original reference

            alert(b);         // Display the changed array [99,2,3] using the new reference

Reference types do not have a fixed size; indeed, some of them can become quite large. As we've already discussed, variables do not directly hold reference values. The value is stored at some other location, and the variables merely hold a reference to that location. Now we need to focus briefly on the actual storage of the value. Since strings, objects, and arrays do not have a fixed size, storage for them must be allocated dynamically, when the size is known. Every time a JavaScript program creates a string, array, or object, the interpreter must allocate memory to store that entity. Whenever memory is dynamically allocated like this, it must eventually be freed up for reuse, or the JavaScript interpreter will use up all the available memory on the system and crash. In languages like C and C++, memory must be freed manually. It is the programmer's responsibility to keep track of all the objects that are created and to destroy them (freeing their memory) when they are no longer needed. This can be an onerous task and is often the source of bugs. Instead of requiring manual deallocation, JavaScript relies on a technique called garbage collection. The JavaScript interpreter is able to detect when an object will never again be used by the program. When it determines that an object is unreachable (i.e., there is no longer any way to refer to it using the variables in the program), it knows that the object is no longer needed and its memory can be reclaimed. Consider the following lines of code, for example:

            var s = "hello";            // Allocate memory for a string

            var u = s.toUpperCase(  );  // Create a new string

            s = u;                      // Overwrite reference to original string


After this code runs, the original string "hello" is no longer reachable -- there are no references to it in any variables in the program. The system detects this fact and frees up its storage space for reuse. Garbage collection is automatic and is invisible to the programmer. You can create all the garbage objects you want, and the system will clean up after you! You need to know only enough about garbage collection to trust that it works;