bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/Working with Data
JavaScript•Working with Data

JavaScript BigInt

Concept visual

JavaScript BigInt

Graph traversalgraph
ABCDE
current
queued
1
4

Start from A

What is JavaScript BigInt?

BigInt is a JavaScript data type for handling and storing big integer values. BigInt allows you to work with integers larger than the limit of Numbers. BigInt can represent an integer of any size, limited only by available memory.

JavaScript Accuracy

JavaScript Numbers are only accurate up to 15 digits:

Example

// 15 digits:

let x = 999999999999999;

// 16 digits:

let y = 9999999999999999;

Formula

Numbers are 64 - bits Floating Point

All JavaScript

Numbers are stored in a

Formula

64 - bit floating - point format (IEEE 754 standard).

With this standard, large numbers cannot be exactly represented, but will be rounded. JavaScript can only safely represent integers up to

53 -1 (9007199254740991). JavaScript can only safely represent integers down to -2 53 -1 (-9007199254740991).

Examples

// MAX = 9007199254740991 let x = Number.MAX_SAFE_INTEGER;
// MIN = -9007199254740991 let y = Number.MIN_SAFE_INTEGER;

Integers bigger than

Number.MAX_SAFE_INTEGER will lose precision: // Max (accurate)

let x = 9007199254740991;

Formula

// Max + 10 (inaccurate)
let y = x + 10;

Integers less than than

Number.MIN_SAFE_INTEGER will lose precision: // Min (accurate)

let x = -9007199254740991;

Formula

// Min - 10 (inaccurate)
let y = x - 10;

There is no such thing as a JavaScript Integer.

Formula

All JavaScript Numbers are 64 - bit floating point.

How to Create a BigInt

You can create a BigInt in two ways:

Using an integer literal with an n

suffix

Using the

BigInt()

constructor with a string

Examples

// Using an integer literal with an n suffix:

let x = 999999999999999n;
// Using the BigInt() constructor with a string:
let y = BigInt("999999999999999");
let x = 12345678901234567890n;
let y = BigInt("12345678901234567890")
You can also create a BigInt using the Bigint() constructor with a

Number. Warning !! Numbers are only accurate up to 15 digits.

Examples let x = BigInt(9999999999999999);

BigInt is a JavaScript Datatype

The JavaScript typeof a

BigInt is "bigint":

Example

let x = BigInt(999999999999999);
let type = typeof x;

BigInt is the second numeric data type in JavaScript (after

Number

).

With

BigInt the total number of supported data types in JavaScript is 8:

  1. String 2. Number
  1. Bigint 4. Boolean
  1. Undefined 6. Null
  1. Symbol 8. Object

Arithmetic Operators

BigInt supports standard JavaScript arithmetic operators. (+, -, ++, --, *, /, %, **)

Example

Multiplication

let x = 9007199254740995n;
let y = 9007199254740995n;
let z = x * y;

Mixing BigInt and Numbers

Arithmetic between a

BigInt and a

Number is not allowed (will result in a

Previous

Regular Expression Assertions

Next

JavaScript Array Reference