The next topic we need to consider is the
content of variables. We often say that variables have or contain
values. But just what is it that they contain? To answer this
seemingly simple question, we must look again at the data types
primitive types and reference types. Numbers, boolean values, and the
null and undefined types are primitive. Objects,
arrays, and functions are reference types.
The distinction between primitive and reference types is an important one, as they behave differently. Consider the following code that uses numbers (a primitive type):
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
There is nothing surprising about this code. Now consider what happens if we change the code slightly so that it uses arrays (a reference type) instead of numbers:
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
If this result does not seem surprising to you, you’re already well familiar with the distinction between primitive and reference types. If it does seem surprising, take a closer look at the second line. Note that it is the reference to the array value, not the array itself, that is being assigned in this statement. After that second line of code, we still have only one array object; we just happen to have two references to it.
If the primitive versus reference type distinction is new to you, just try to keep the variable contents in mind. Variables hold the actual values of primitive types, but they hold only references to the values of reference types. The differing behavior of primitive and reference types is explored in more detail in Section 11.2.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.