JavaScript Introducing BigInt Primitive in ES2020

Bigint is a new primitive data type for integers. Bigint doesn’t have a fixed storage size in bits.                      

BigInt literals are written as a string of digits followed by a lowercase letter n. By default, they are in base 10, but you can use the 0b, 0o, and 0x prefixes for binary, octal, and hexadecimal BigInts

A bigint literal is a sequence of one or more digits, suffixed with an n. 

Example

        
762n        
    

Bigints are primitive values. typeof returns a new result for them

        
typeof 762n     // Output : 'bigint'        
    

Let's create more examples to understand Bigint

        
const alsoHuge = BigInt(9007149259840774)        

// Output : 9007149259840774n

const hugeString = BigInt("9007199557690228")     

// Output : 9007199557690228n

const hugeHex = BigInt("0x2fffffffffffff")                 

// Output : 13510798882111488n

const hugeOctal = BigInt("0o477777777777777777")  

// Output : 11258999068426240n
        
    

BigInt values are similar to Number values in some ways, but also differ in a few key matters: 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.

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

 +  *  -  % **

        
const str = 68014396409791981n - 10n   
// Output : 68014396409791971n

const str = 68014396409791981n + 10n   
// Output : 68014396409791991n

const str = 68014396409791981n *  10n   
// Output : 680143964097919810n

const str =  2n ** 66n   
// Output : 73786976294838206464n        
    

BigInt values and Number values may be mixed in arrays and sorted

        
const str = [8n, 2, -9n, 11, 42, 0, 0n]
console.log(str.sort());

// Output : Array [-9n, 0, 0n, 11, 2, 42, 8n]        
    

BigInt values behave with logical operators like this.

        
const mixed = 0n || 12n
// Output : 12n

const mixed = 0n && 9n
// Output :  0n      
   
const mixed = !12n
// Output : false        
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top