Main Page

Primitive Types

When a value is assigned to a variable, the ECMAScript interpreter must decide if it is a primitive or ref-
erence value. To do this, the interpreter tries to determine if the value is one of the ECMAScript
: Undefined, Null, Boolean, Number, or String. Because each one of these primitive types takes up a
fixed amount of space, it can be stored in the small memory area known as the stack. Doing so allows for
quick look up of variable values.
In many languages, strings are considered a reference type and not a primitive type because a string can
vary in length. ECMAScript breaks from this tradition.
If the value is a reference, then space is allocated on the heap. Because a reference value’s size can vary, it
cannot be placed on the stack because it would reduce the speed of variable lookup. Instead, the value
placed in the variable’s stack space is an address of a location in the heap where the object is stored. This
address does have a fixed size; so storing it in the stack has no negative effect on variable performance
(Figure 2-1).
Figure 2-1
Primitive Types
As mentioned previously, ECMAScript has five
primitive types
: Undefined, Null, Boolean, Number, and
String. ECMA-262 defines the term
as a set of values, and each of the primitive types defines a range
of values it can contain as well as literal representations of that type. To determine if a value is in the
range of values for a particular type, ECMAScript provides the
operator. This operator can be
used to determine if a value represents a primitive type and, if so, which primitive type it represents.
The typeof operator
operator takes one parameter: the variable or value to check. For example:
boolean(tr ue)
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 16

JavaScript EditorFree JavaScript Editor     Ajax Editor