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 = 99; // Modify the array using the original reference alert(b); // Display the changed array [99,2,3] using the new reference
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;