Search This Blog

2023/07/26

BigInt in javascript

 BigInt values represent numeric values which are too large to be represented by the number

It is created by appending n to the end of an integer literal,
or by calling the BigInt() function
e.g.
const bigIntNumber = 1n;


A BigInt value cannot be used with methods in the built-in Math
object and cannot be mixed with a Number value in operations;
they must be coerced to the same type. however, as the precision of
a BigInt value may be lost when it is coerced to a Number value.

typeof 1n === "bigint"; // true
typeof BigInt("1") === "bigint"; // true


A BigInt value can also be wrapped in an Object:

typeof Object(1n) === "object"; // true

Comparision:

0n === 0; // false different types
0n == 0; // true


Sorting:
const mixed = [4n, 6, -12n, 10, 4, 0, 0n];
mixed.sort((a, b) => a - b);

sorting using previous function won't work since subtraction will
not work with mixed types

You will get follwoing error:
TypeError: can't convert BigInt value to Number value


How to sort mixed array with bigInt

mixed.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));


The following operators may be used with BigInt values or object-wrapped
BigInt values:

+ * - % **


Also unsupported is the unary operator (+),

Here consider following code

var x = 1n
var y = 5
console.log(y - x)

we get error as
TypeError: Cannot mix BigInt and other types, use explicit conversions


with explicit conversion

var x = 1n
var y = 5
console.log(BigInt(y) - x)

output:
4n

Negative BigInt

Consider following code

var x = -1n
var y = 5
console.log(BigInt(y) - x)

Output:
6n

No comments:

Post a Comment