# JavaScript Bigint

The `bigint` is a new primitive data type in JavaScript. It was introduced in ES11 version of JavaScript. it represents the whole number. It can hold numbers larger than 253 – 1. The BigInt uses the arbitrary-precision arithmetic. This article covers how to use bigInt, the arithmetic operations allowed, how to convert bigint to number and number to bigint, etc.

## Defining bigint

There are two ways in which you create `bigint`.

A `bigInt` is created by appending `n` to the end of an integer literal

You can even use binary, octal or hexadecimal notation. Just use `n` at the end. Legacy octal syntax (`0640`) is not allowed, only new-style (`0o064n`).

or by calling the function Global function `BigInt()`

Hex, binary & octal numbers.

## Max Value

The `bigint` can handle the large values and not limited as the `Number` datatype, which has (Number.MAX_SAFE_INTEGER). BigInt is limited by the available memory of the host system

## Arithmetic Operations

The `BigInt` can be used with the following arithmetic operations `+``*``-``**``%`. Bitwise operators like ` &`, ` |` , `^` , ` ~`, `<<` , `>>`, (except `>>>` Zero fill right shift) operators.

The unary operator + is not supported. Also `>>>` is not supported, as all BigInts are signed

The `/` division operator rounds of the final result to the whole number. For example, dividing 5/2 results in 2 and not 2.5. i.e it is an integer and not decimal.

`bigint` can not be mixed with operations where numbers are involved as shown below. Either you convert number to bigint or convert bigint to number.

## Convert Number to BigInt

You can use the `BigInt` function to convert the `number` to a `bigInt`

## Convert BigInt to Number

You can convert the `bigInt` to `number` by using the Number function. Beware of the fact that you may lose precision when you coerce `bigint` to `number`.

## Comparison operators

The comparison operators work well between `bigInt` and a `number`

`BigInt` 0 is loosely equal (`0n==0` is `true`) to number 0.  But is not strictly equal to a `Number` (`0n===0` is `false`)

## Conditionals

`BigInt` behaves like a `Number` when converted to Boolean.

## Summary

The `bigint` is a primitive type. It is added so as to support the large number. bigint cannot be used in the operations involving numbers. They must be coerced to do that. Beware of the fact that you may lose precision when you coerce `bigint` to `number` and back. You can make use of comparison operators to compare `bigInt` with a `number`.

Scroll to Top