JavaScript Data Types with Examples & Usage

1. String

Definition: A sequence of characters used for text.

Example:

let name = "Alice";

Use: Store names, messages, sentences, etc.

Why: Easy to handle user input and display text.

When: Any time you work with text or words.

Know more in Detail

2. Number

Definition: Represents both integers and floating-point numbers.

Example:

let age = 25;
let price = 9.99;

Use: For calculations, measurements, scores, prices.

Why: Essential for math and logic operations.

When: Anytime you need numeric values.

Know more in Detail

3. Boolean

Definition: Represents either true or false.

Example:

let isOnline = true;

Use: For conditional checks and logic (like login status).

Why: Controls program flow (e.g., show/hide UI).

When: Use when result is yes/no, on/off, true/false.

4. Undefined

Definition: A variable declared but not assigned a value.

Example:

let score;
console.log(score); // undefined

Use: Detect uninitialized variables.

Why: Helps find bugs or logic errors.

When: Happens automatically if no value is assigned.

5. Null

Definition: Intentional absence of value (manually assigned).

Example:

let data = null;

Use: Reset or empty a variable intentionally.

Why: Tells program that a value is purposely "nothing".

When: Use when a variable will later be given data.

6. BigInt

Definition: Used to store very large integers beyond the normal range.

Example:

let big = 1234567890123456789012345678901234567890n;

Use: Store large numbers like those in cryptography or math.

Why: Normal numbers may lose precision.

When: Numbers > 253 or need full precision.

7. Symbol

Definition: A unique, immutable identifier (often used as keys).

Example:

let sym = Symbol("id");

Use: Add hidden properties to objects.

Why: Avoid property name collisions.

When: Advanced use cases like meta-programming.

8. Object

Definition: A collection of key-value pairs.

Example:

let person = { name: "Alice", age: 25 };

Use: Store structured data (e.g., users, products).

Why: Very flexible and powerful data container.

When: When storing grouped or nested values.

9. Array

Definition: A list of values stored in a single variable.

Example:

let fruits = ["apple", "banana", "mango"];

Use: Store collections of data like lists or tables.

Why: Easy to loop and manage multiple items.

When: When data has an order or needs iteration.

10. Function

Definition: A reusable block of code to perform a task.

Example:

function greet(name) {
  return "Hello " + name;
}

Use: Organize logic into reusable units.

Why: Helps with code reuse, clarity, and testing.

When: Use for repeated tasks or actions.