ECMAScript 初值和引用值
- Previous page Reserved Words in ECMAScript
- Next page Primitive Types in ECMAScript
In ECMAScript, variables can have two types of values, namely primitive values and reference values.
Primitive values and reference values
In ECMAScript, variables can have two types of values, namely primitive values and reference values.
- Primitive value
- Stored in the stack (stack) as a simple data segment, that is, their values are directly stored at the location accessed by the variable.
- Reference value
- Stored in the heap (heap), that is, the value stored in the variable is a pointer (point) to the memory location where the object is stored.
When assigning a value to a variable, the ECMAScript interpreter must determine whether the value is a primitive type or a reference type. To achieve this, the interpreter needs to try to determineWhether the value is one of the primitive types of ECMAScriptthat is, Undefined, Null, Boolean, Number, and String. Since these primitive types occupy a fixed amount of space, they can be stored in a smaller memory area - the stack. This storage is convenient for quickly searching for variable values.
In many languages, strings are considered reference types rather than primitive types because the length of strings is variable. ECMAScript breaks this tradition.
If a value is of reference type, its storage space will be allocated from the heap. Since the size of the reference value can change, it cannot be placed in the stack, otherwise it will slow down the variable search speed. Instead, the value stored in the stack space of the variable is the address of the object stored in the heap. The size of the address is fixed, so storing it in the stack has no negative impact on the variable performance. As shown in the following figure:

Primitive type
As mentioned earlier, ECMAScript has 5 primitive types (primitive type), namely Undefined, Null, Boolean, Number, and String. ECMA-262 defines the termType (type)Defined as a collection of values, each primitive type defines the range of values it contains and its literal representation form.
ECMAScript provides the typeof operator to determine whether a value is within a certain type range. This operator can be used to determine whether a value represents a primitive type: if it is a primitive type, it can also determine which primitive type it represents.
In later chapters, we will delve deeper into the primitive and reference types of ECMAScript for you.
- Previous page Reserved Words in ECMAScript
- Next page Primitive Types in ECMAScript