JavaScript Data Types
JavaScript is a dynamically typed language, meaning variables can hold any type of data, and types are determined at runtime. Data types fall into two categories: primitive types and reference types.
🔢 1. Primitive Data Types
- String – Represents text:
"Hello"
,'World'
- Number – Both integers and floating-point:
42
,3.14
- Boolean – True or false:
true
,false
- Undefined – A declared variable with no value
- Null – An intentional absence of any object value
- BigInt – For very large integers:
12345678901234567890n
- Symbol – Unique and immutable value often used as object keys
let name = "Alice"; // String
let age = 30; // Number
let isAdmin = true; // Boolean
let x; // Undefined
let empty = null; // Null
let big = 12345678901234567890n; // BigInt
let id = Symbol("id"); // Symbol
🧩 2. Reference (Non-Primitive) Types
- Object – Collection of key-value pairs
- Array – Ordered list of values
- Function – A block of code that can be called
- Date, RegExp, Error – Built-in object types
let person = { name: "Alice", age: 30 }; // Object
let colors = ["red", "green", "blue"]; // Array
function greet() {
console.log("Hello!");
} // Function
📊 3. Type Checking with typeof
You can check the type of a variable using the typeof
operator:
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (quirk in JS!)
typeof {} // "object"
typeof [] // "object"
typeof function() {} // "function"
⚠️ Note:
typeof null
returns "object"
due to a historic bug in JavaScript.
🧠 Summary
JavaScript has 8 basic data types:
- String
- Number
- Boolean
- Undefined
- Null
- BigInt
- Symbol
- Object
Best Practice: Learn to distinguish between primitive and reference types. Understanding how they are stored and compared will help you avoid bugs.