# BigInt

`BigInt` is a built-in object in JavaScript that provides a way to represent whole numbers larger than $2^{53} - 1$, which is the largest number JavaScript can reliably represent with the `Number` primitive.

## 1. Creating BigInts

You can create a `BigInt` by appending `n` to the end of an integer literal or by calling the `BigInt()` function.

```javascript
const theBiggestInt = 9007199254740991n;

const alsoHuge = BigInt(9007199254740991);
// ↪ 9007199254740991n

const hugeString = BigInt("9007199254740991");
// ↪ 9007199254740991n
```

## 2. Why do we need it?

The `Number` type in JavaScript is a double-precision float. It has a "safe integer" limit (`Number.MAX_SAFE_INTEGER`). Beyond this limit, calculations become imprecise.

```javascript
const max = Number.MAX_SAFE_INTEGER; // 9007199254740991

console.log(max + 1); // 9007199254740992 (Correct)
console.log(max + 2); // 9007199254740992 (Wrong! Should be ...93)
```

With `BigInt`, precision is preserved:

```javascript
const maxBig = 9007199254740991n;
console.log(maxBig + 2n); // 9007199254740993n (Correct)
```

## 3. Operations

You can use standard operators (`+`, `*`, `-`, `**`, `%`) with BigInts.

```javascript
const huge = 10n;
console.log(huge + 10n); // 20n
console.log(huge * 2n);  // 20n
console.log(huge / 2n);  // 5n
```

**Note on Division:** Since BigInts are integers, division rounds towards zero (truncates the decimal part).
```javascript
console.log(5n / 2n); // 2n (not 2.5n)
```

## 4. Mixing Types

You **cannot** mix `BigInt` and other types in standard operations. You must perform explicit conversion.

```javascript
const bigint = 1n;
const number = 2;

// console.log(bigint + number); // TypeError: Cannot mix BigInt and other types

console.log(Number(bigint) + number); // 3
console.log(bigint + BigInt(number)); // 3n
```

## 5. Comparisons

*   **Strict Equality (`===`):** `0n === 0` is `false` (different types).
*   **Loose Equality (`==`):** `0n == 0` is `true`.
*   **Relational (`<`, `>`):** Works as expected across types. `1n < 2` is `true`.

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/data-types]]