BigInt in JavaScript
Miscellaneous: BigInt
Can you briefly explain what a BigInt is in JavaScript?
View Answer:
Interview Response: BigInt is a unique numeric type that allows integers of any length. A BigInt gets formed by attaching n to the end of an integer literal or by using the BigInt function, which generates BigInts from strings and numbers.
Technical Response: BigInt is a unique numeric type that allows integers of any length. A BigInt gets formed by attaching n to the end of an integer literal or by using the BigInt function, which generates BigInts from strings, numbers. BigInt gets used chiefly as a regular integer. All operations on BigInts return BigInts. BigInts and regular numbers cannot be blended. If necessary, we should explicitly convert them using BigInt() or Number(). The conversion procedures are always quiet and never produce errors, but if the BigInt is too huge, it won’t fit the number type, and excess bits get chopped off; thus, we should exercise caution while doing such conversions.
Code Example:
const bigint = 1234567890123456789012345678901234567890n;
const sameBigint = BigInt('1234567890123456789012345678901234567890');
const bigintFromNumber = BigInt(10); // same as 10n
alert(1n + 2n); // 3
alert(5n / 2n); // 2
alert(1n + 2); // Error: Cannot mix BigInt and other types
let bigint = 1n;
let number = 2;
// number to bigint
alert(bigint + BigInt(number)); // 3
// bigint to number
alert(Number(bigint) + number); // 3
How does the division operator interact with BigInts?
View Answer:
Interview Response: When we use BigInts with the division operator, it rounds the BigInt towards zero. All operations on BigInts return BigInts.
Code Example:
// Regular Numbers
alert(5 / 2); // 2.5
// BigInt
alert(5n / 2n); // 2, rounds towards zero
What happens when you mix regular numbers with BigInts?
View Answer:
Interview Response: We should never mix BigInts and regular numbers in mathematical operations because they result in errors. If needed, we should explicitly convert them using BigInt() or Number().
Code Example:
alert(1n + 2); // Error: Cannot mix BigInt and other types
// Explicit Conversion
let bigint = 1n;
let number = 2;
// number to bigint
alert(bigint + BigInt(number)); // 3
// bigint to number
alert(Number(bigint) + number); // 3
Is it possible to use the unary operator on BigInts?
View Answer:
Interview Response: No, we should use Number() to convert a BigInt to a number.
Code Example:
let bigint = 1n;
console.log(Number(bigint)); // returns 1
console.log(+bigint); // TypeError
Although comparisons work with BigInt, what should you always remember?
View Answer:
Interview Response: Comparisons, such as (‹ ›) work with BigInts and numbers without issue, but as numbers and BigInts belong to different types, they can be equal ==, but not strictly equal === each other.
Code Example:
alert(1 == 1n); // true
alert(1 === 1n); // false