Course contentsShow
← JavaScript
Lesson 132 of 2,7234. Working with NumbersFree lesson

BigInt Type Checking and Conversion

Use typeof to detect BigInt, and convert safely with BigInt() and Number() while avoiding precision loss.

BigInt Type Checking and Conversion

You'll learn how to identify BigInt values with typeof and safely convert between BigInt and Number without losing data.

Checking if a Value is BigInt

Just like you can use typeof to check for "number" or "string", you can detect BigInt values:

typeof 42n          // "bigint"
typeof 123          // "number"
typeof BigInt(100)  // "bigint"

This is useful when you need to verify what type of numeric value you're working with.

Converting Number to BigInt

Use the BigInt() function (without new) to convert a Number to BigInt:

BigInt(42)      // 42n
BigInt(100)     // 100n

Warning: Only integers can be converted safely. Decimals will cause an error:

BigInt(3.14)    // RangeError: The number 3.14 cannot be converted to a BigInt

Converting BigInt to Number

Use the Number() function to convert BigInt back to Number:

Number(42n)     // 42
Number(100n)    // 100

Critical caveat: If the BigInt is larger than Number.MAX_SAFE_INTEGER, you'll lose precision:

const huge = 9007199254740992n;
Number(huge);   // 9007199254740992 ✓ (still safe)

const tooBig = 9007199254740993n;
Number(tooBig); // 9007199254740992 ✗ (precision lost!)

Think of it like this: Converting BigInt to Number is like pouring from a very large bucket into a smaller cup—if there's too much, it overflows and you lose the excess.

When to Convert

Only convert BigInt to Number when you're certain the value fits within the safe integer range. Always verify with Number.isSafeInteger() after conversion if precision matters.

Key Takeaway: Use typeof to check for "bigint", convert with BigInt() for integers only, and use Number() carefully to avoid precision loss beyond the safe integer range.