Primitive Data Types in JavaScript
Primitive data types are the basic building blocks of JavaScript. They represent single, immutable values (not objects) and are stored directly in memory.
When you assign a primitive value to a variable, that variable holds the actual data β not a reference.
What Are Primitive Data Types?β
JavaScript has 7 primitive data types:
| Type | Description | Example |
|---|---|---|
| String | Textual data enclosed in quotes | "Ajay" |
| Number | Numeric values (integer or float) | 42, 3.14 |
| Boolean | Logical values | true, false |
| Undefined | Declared but not assigned any value | let x; |
| Null | Intentional absence of any value | let y = null; |
| BigInt | Large integers beyond Numberβs limit | 12345678901234567890n |
| Symbol | Unique and immutable identifiers | Symbol("id") |
Key Characteristicsβ
-
Immutable:
Once created, their value cannot be changed.let name = "Ajay";
name[0] = "a"; // β Doesn't change the original string
console.log(name); // "Ajay" -
Stored by Value: When assigned or passed, a copy of the value is made.
let a = 10;
let b = a;
b = 20;
console.log(a); // 10 (not affected) -
Fixed Memory Size: Each primitive type has a known, fixed amount of memory.
Primitive Data Types in Actionβ
1. Stringβ
Used for representing text.
let message = "Hello, World!";
let greeting = 'Hi!';
let template = `Welcome, ${message}`;
2. Numberβ
Represents both integer and floating-point numbers.
let count = 42;
let price = 9.99;
let infinity = Infinity;
let notANumber = NaN;
3. Booleanβ
Represents logical truth values.
let isOnline = true;
let hasAccess = false;
4. Undefinedβ
A variable declared but not initialized.
let x;
console.log(x); // undefined
5. Nullβ
Represents the intentional absence of any object value.
let user = null;
console.log(user); // null
6. BigIntβ
Used for numbers larger than the safe integer limit (2^53 - 1).
let bigNumber = 123456789012345678901234567890n;
7. Symbolβ
Used for creating unique, immutable identifiers (often used in objects).
let id = Symbol("id");
let anotherId = Symbol("id");
console.log(id === anotherId); // false
Type Checking with typeofβ
You can check a variableβs type using the typeof operator:
console.log(typeof "Hello"); // string
console.log(typeof 42); // number
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object (a historical JS bug)
console.log(typeof 123n); // bigint
console.log(typeof Symbol()); // symbol