JavaScript Data Types Explained
In JavaScript, data types define the kind of data a variable can hold. Understanding data types helps you write better, bug-free code. Let's explore the two main categories: Primitive and Reference types.
1. Primitive Data Types
Primitive types are basic, immutable values stored directly in memory. JavaScript has 7 of them:
- String
- Number
- Boolean
- Null
- Undefined
- Symbol (ES6)
- BigInt (ES11)
🔤 String
Used for textual data.
let name = "Alice";
let greeting = 'Hello!';
let message = `Hi, ${name}`;
🔢 Number
Used for both integers and decimals.
let age = 30;
let price = 99.99;
✅ Boolean
Represents either true
or false
.
let isLoggedIn = true;
let isAdmin = false;
❌ Null
Intentional absence of any value.
let user = null;
🌀 Undefined
A variable declared but not assigned a value.
let score;
console.log(score); // undefined
🔣 Symbol
A unique and immutable primitive value, often used as object keys.
const id = Symbol("id");
const id2 = Symbol("id");
console.log(id === id2); // false
🔢 BigInt
Used for very large integers beyond the safe integer limit.
const bigNumber = 1234567890123456789012345678901234567890n;
2. Reference Data Types
Reference types are objects stored as references in memory.
- Object
- Array
- Function
- Date, RegExp, etc.
📦 Object
const user = {
name: "Alice",
age: 25
};
📚 Array
const colors = ["red", "green", "blue"];
🔧 Function
function greet(name) {
return `Hello, ${name}`;
}
3. Checking Data Types
Use the typeof
operator to check a variable's type.
typeof "hello" // string
typeof 123 // number
typeof false // boolean
typeof undefined // undefined
typeof null // object (quirk!)
typeof {} // object
typeof [] // object
typeof function(){} // function
4. Summary Table
Data Type | Category | Example |
---|---|---|
String | Primitive | "Hello" |
Number | Primitive | 123, 45.6 |
Boolean | Primitive | true / false |
Null | Primitive | null |
Undefined | Primitive | undefined |
Object | Reference | { name: "John" } |
Array | Reference | [1, 2, 3] |
✅ Pro Tip: Always use
typeof
to safely check your variable types!