# Datatypes

Datatypes are the type of data a variable can store

- Primitive types
- Reference types

## 🧱 Primitive Types

| Type | description | Example |
| --- | --- | --- |
| Number | Both integers and floating-point numbers (Number literal) | `5`, `5.55`, `Infinity`, `NaN` |
| String | Textual data wrapped in quotes (String literal) | "Hi", 'Hi', \`Hi\` |
| Boolean | Logical values: true or false | `true`, `false` |
| Undefined | A variable that has been declared but not assigned | `undefined` |
| Null | An intentional absence | `null` |

#### Example

```js
let age = 15;
let name = "Rohan";
let isAdult = false;
let Lisence = undefined; // When it is not needed when empty
let favMovie = null; // When it is needed even when empty
```

### 🎭 Dynamic typing

JS is a dynamic language i.e., the type of the variable can change during runtime.

```js
let data = 42;      // data is a Number
data = "Forty-two"; // data is now a String
data = true;        // data is now a Boolean
```

## 🧩 Reference Types

| Type | description | Example |
| --- | --- | --- |
| Object | A collection of properties | `{ name: "John", age: 30 }` |
| Array | A list of values | `[1,2,3]` |
| Function | A block of code | `() => {console.log("Hello Javascript")}` |

### ⚖️ Primitive vs Reference Types

The main difference is how values are copied during assignment.

| Feature | Primitive Types | Reference Types |
| --- | --- | --- |
| Assignment | Copies the value | Copies the reference |
| Changes | Independent values | Variables can refer to the same object |
| Examples | `Number`, `String`, `Boolean` | `Object`, `Array`, `Function` |

#### Primitive — Copy by Value

```js
let a = 10;
let b = a;
b = 20;

console.log(a); // 10
console.log(b); // 20
```

#### Reference — Shared Object

```js
let a = { score: 10 };
let b = a;
b.score = 20;

console.log(a.score); // 20
console.log(b.score); // 20
```

Both variables refer to the same object, so modifying its properties through one variable affects the other.

> *Note*
>
> JavaScript technically copies all assigned values. For objects, the copied value is a reference to the same object.

## 🔀 Type conversion

Explicitly convert varaible from one datatype to another.\
Eg: String -> Number, Boolean -> String

### typeof keyword

typeof keyword is used to check the data type of a variable

```js
let data = 10;
console.log(typeof data); //Number
```

JS has a bunch of built-in ways to convert types. Think of them in 3 buckets: string, number, boolean

### Convert to string

```js
String(123) // "123"
(true).toString // "true"
```

### Convert to Number

```js
Number("123") // 123
praseInt("456abc") // 456
**NOTE**
Number("123go") // NaN
```

### Convert to Boolean

```js
Boolean(0) // false
Boolean("Hello") // true
```
