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
๐ง Summaryโ
| Feature | Primitive Types |
|---|---|
| Stored As | Value |
| Mutable | โ No |
| Copied By | Value |
| Examples | String, Number, Boolean, Undefined, Null, BigInt, Symbol |