Data types
JavaScript has two main categories of data types:
- Primitive Data Types (immutable, stored by value)
- Non-Primitive (Reference) Data Types (mutable, stored by reference)
1. Primitive Data Types
Primitive types hold single values and are immutable.
Data Type | Description | Example |
---|---|---|
Number | Represents integers and floating-point numbers | let age = 25; |
String | Represents text (sequence of characters) | let name = "Alice"; |
Boolean | Represents true or false | let isActive = true; |
Undefined | A variable that has been declared but not assigned a value | let x; |
Null | Represents an empty or non-existent value | let data = null; |
Symbol (ES6) | Unique and immutable identifier | let id = Symbol("id"); |
BigInt (ES11) | For numbers larger than 2^53 - 1 | let bigNum = 12345678901234567890n; |
Example:
let num = 42; // Number
let text = "Hello"; // String
let isReady = false; // Boolean
let emptyValue = null; // Null
let notAssigned; // Undefined
let uniqueID = Symbol(); // Symbol
let largeNumber = 123n; // BigInt
2. Non-Primitive (Reference) Data Types
Reference types hold collections of values and are mutable.
Data Type | Description | Example |
Object | Collection of key-value pairs | { name: "Alice", age: 25 } |
Array | Ordered list of values | [1, 2, 3, "hello"] |
Function | Block of reusable code | function greet() { console.log("Hi!"); } |
Example:
// Object
let person = { name: "Alice", age: 25 };
// Array
let numbers = [10, 20, 30, 40];
// Function
function greet() {
return "Hello, World!";
}
Checking Data Types
You can check a variable’s data type using typeof:
console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (JavaScript bug)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"