In JavaScript, there are two types of data types.
- Primitive Data Type
- Non-Primitive Data Type.
Primitive Data Type
What is a Primitive Data Type?
Primitives are basic data types that are not objects and have no methods. Primitives are immutable (can't be changed), meaning their values cannot be changed once created. We will get to details after a while — let's get to know what primitive data types are.
String
- String
const name = "Alice";
- Number
const age = 25;
- BigInt
const big = 1234567890123456789012345678901234567890n;
- Boolean
const isActive = true;
- Undefined
let x;
console.log(x); // undefined
- Null
const empty = null;
- Symbol
const sym = Symbol("id");
You might have one question in mind.
If string is a primitive data type, it means it doesn't have any methods and it's immutable.
But we know strings have methods like toUpperCase()
, etc.? Well, you are right. Let's understand in detail.
When we use a method on any primitive (like string), JavaScript automatically wraps it in its corresponding object type so that we can access object-like methods.
Example:
const str = "hello";
const upperStr = str.toUpperCase();
console.log(upperStr); // "HELLO"
What JavaScript does internally (conceptually):
// Step 1: You have a primitive string
let str = "hello"; // primitive string
// Step 2: JavaScript wraps it in a String object (temporary)
let tempStrObject = new String(str); // [object String]
// Step 3: Call the method on that object
let result = tempStrObject.toUpperCase(); // "HELLO"
// Step 4: Discard the object, return result
Important:
str
is still"hello"
. The original primitive is unchanged because it's immutable.
Non-Primitive Data Type
Non-primitives are the opposite of primitives. Non-primitives are types that are not primitive.
Important: They are stored by reference, not by value.
Let's understand by an example
Primitive (stored by value)
let a = 10;
let b = a; // b gets a copy of the value of a (10)
b = 20;
console.log(a); // 10 — ❗ a is unaffected
Non-primitive (stored by reference)
let obj1 = { name: "Alice" };
let obj2 = obj1; // obj2 references the same object in memory
obj2.name = "Bob";
console.log(obj1.name); // "Bob" — ❗ obj1 is affected
Both obj1
and obj2
point to the same object in memory, so changing it through one affects the other.
Top comments (0)