Primitive and Reference Data Types
JavaScript data types are mainly divided into primitive
and reference
.
These two types are different in how values are stored and referenced.
1. Primitive Types
In JavaScript, the primitive data types are as follows:
-
Number
: numbers (e.g.,5
,3.14
) -
String
: text strings (e.g.,"Hello"
) -
Boolean
: true or false values (true
orfalse
) -
Undefined
: variables that haven't been assigned a value (undefined
) -
Null
: signifies no value (null
) -
BigInt
: large integers (e.g.,1234567890123456789012345678901234567890n
) -
Symbol
: unique and immutable value
Characteristics of Primitive Data:
-
Once created, the primitive data value cannot be changed.
-
When assigning to another variable, the value itself is copied.
let a = 10; let b = a; // the value is copied and assigned to variable b b = 20; console.log(a); // 10 console.log(b); // 20
2. Reference Types:
Reference types store addresses in memory (the computer's storage space).
In simple terms, instead of storing the actual value, the "address" where the data is located in the computer is saved in the variable.
The main reference types in JavaScript are as follows:
-
Object
: objects -
Array
: arrays -
Function
: functions
Characteristics of Reference Data:
-
When assigning reference data to another variable, it copies the memory address where the data is stored rather than the data itself.
-
Both the assigned variable and the variable given the value point to the same memory location (address where the data is stored).
let obj1 = { name: 'John Doe' }; let obj2 = obj1; // reference copy, copies the address where the data is stored to obj2 obj2.name = 'John Smith'; // Since obj1 and obj2 both point to the same address, changing the name in obj2 also changes it in obj1 console.log(obj1.name); // 'John Smith' console.log(obj2.name); // 'John Smith'
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result