# Data Types

JavaScript is a **dynamically typed** language. This means variables are not bound to a specific data type; you can assign a number to a variable and later assign a string to that same variable.

### 1. The Two Categories

JavaScript data types are divided into two distinct categories: **Primitives** and **Objects**.

<figure><img src="https://999998466-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQ1dYgkEA7yduHqSM10cn%2Fuploads%2FpEcLMrDG3dZgqB7ciMf7%2Fimg_datatypes_500.jpg?alt=media&#x26;token=33083076-dd4c-416c-aaf4-88e96b18d94a" alt=""><figcaption></figcaption></figure>

#### A. Primitives (The "Atoms")

Primitives are the simplest forms of data. They are **immutable**, meaning their value cannot be changed once created (though the variable holding them can be reassigned).

There are 7 primitive types:

1. **Number:** Floating-point numbers (there is no specific "integer" type in JS).
   * *Examples:* `42`, `3.14`, `-10`.
   * *Special values:* `Infinity`, `NaN` (Not a Number).
2. **String:** A sequence of characters.
   * *Examples:* `"Hello"`, `'World'`, `` `Backticks` ``.
3. **Boolean:** Logical entities.
   * *Values:* `true`, `false`.
4. **Undefined:** A variable that has been declared but not assigned a value.
   * *Value:* `undefined`.
5. **Null:** Represents the intentional absence of any object value.
   * *Value:* `null`.
6. **BigInt:** For integers larger than the `Number` type can safely represent (`2^53 - 1`).
   * *Example:* `9007199254740991n`.
7. **Symbol:** Unique and immutable identifiers, often used for object keys.

#### B. Objects (The "Collections")

Objects are collections of properties. Unlike primitives, objects are **mutable**.

* **Object:** `{ name: "Alice", age: 25 }`
* **Array:** `[1, 2, 3]` (Arrays are technically special objects).
* **Function:** Code blocks designed to perform tasks (also objects).
* **Date, RegExp, Map, Set:** Built-in complex structures.

### 2. How JavaScript Treats Them: Value vs. Reference

The most important distinction between Primitives and Objects is how they are stored and copied.

#### Primitives: Passed by Value

When you assign a primitive to a variable, the variable stores the **actual value**.

```
let a = 10;
let b = a;  // Copy the value (10) to b

b = 20;     // Change b

console.log(a); // 10 (a is untouched)
console.log(b); // 20


```

#### Objects: Passed by Reference

When you assign an object to a variable, the variable stores a **reference (memory address)** pointing to where that object lives in memory, not the object itself.

```
let x = { name: "Alice" };
let y = x;  // Copy the REFERENCE (address) to y

y.name = "Bob"; // Modify the object at that address
 
console.log(x.name); // "Bob" (x sees the change too!)


```

*Because `x` and `y` point to the exact same location in memory, changing one affects the other.*

### 3. Type Conversion (Coercion)

Because JavaScript is dynamic, it often converts types automatically. This is called **Implicit Coercion**. You can also force a change using **Explicit Conversion**.

#### A. Explicit Conversion (Manual)

This is when you tell JS exactly what you want. It is safer and more readable.

```
let str = "123";
let num = Number(str);  // Becomes 123 (number)

let val = 0;
let bool = Boolean(val); // Becomes false

let date = String(new Date()); // Converts date object to string


```

#### B. Implicit Coercion (Automatic)

This happens when you apply operators to mismatched types.

**1. String Concatenation wins over Math**

If you use `+` and one side is a string, JS converts the other side to a string.

```
let res = "5" + 2; // "52" (String)
let res2 = "5" + true; // "5true" (String)


```

**2. Math wins with other operators**

If you use `-`, `*`, `/`, or `%`, JS tries to convert strings to numbers.

```
let res = "10" - 2; // 8 (Number)
let res2 = "10" * "2"; // 20 (Number)
let res3 = "10" - "apple"; // NaN (Not a Number)


```

**3. Equality: `==` vs `===`**

* **Double Equals (`==`):** Allows coercion. It converts types to match before comparing.
  * `5 == "5"` is `true`.
  * `0 == false` is `true`.
  * `null == undefined` is `true`.
* **Triple Equals (`===`):** Strict equality. No coercion allowed. **Always use this.**
  * `5 === "5"` is `false`.

### 4. Truthy and Falsy Values

When a value is expected to be a Boolean (like in an `if` statement), JS converts it.

**Falsy Values (There are only 6):**

1. `false`
2. `0` (and `-0`)
3. `""` (empty string)
4. `null`
5. `undefined`
6. `NaN`

**Truthy Values:**

Everything else.

* `"0"` (non-empty string) -> true
* `[]` (empty array) -> true
* `{}` (empty object) -> true
* `function(){}` -> true

### 5. The "Gotcha" of Typeof

You can check a variable's type using the `typeof` operator, but there are quirks.

```
typeof "Hello"   // "string"
typeof 42        // "number"
typeof true      // "boolean"
typeof undefined // "undefined"
typeof {a:1}     // "object"
typeof [1,2]     // "object" (Arrays are objects!)
typeof function(){}// "function"

// THE BUG
typeof null      // "object"


```

*Note: `typeof null` returning "object" is a historical bug in JavaScript that cannot be fixed without breaking existing code on the internet. `null` is actually a primitive.*
