Do You Know When To Use JavaScript BigInt? ??
Vinicius Guterres ????
Full-Stack Developer at @Spacecom | TypeScript, Node.js, Nest.js | React | PostgreSQL, MongoDB | SQL, NoSQL | AWS Cloud
As a JavaScript programmer, I can confidently say that I rarely use the JS type "BigInt" in my daily problem-solving tasks. So, why am I writing an entire post about a tool I seldom use? In this article, I hope to answer that question.
Ok, let's start from the beginning...
A Simple Algorithm Challenge ??
I was solving a coding challenge that involved numbers and price comparisons.
Here’s a summary of the challenge:
Challenge Description
Context:
The function provides:
Main Goal: Return the minimum cost to buy the gifts.
After carefully reading the description and understanding the problem, the logic to solve it seems quite easy, right?
Yes! The logic behind this challenge is very straightforward.
here's my first solution code:
To briefly explain: my function takes five parameters - the total number of black and white gifts to buy, their prices, and the exchange cost.
The core idea is to check whether it's cheaper to buy a gift at its current price or to buy a gift of the opposite color and then convert it using the exchange price.
This comparison was easily handled using Javascript "Math.min()" method to determine the minimum cost for both black and white gifts.
Finally, I returned the total cost of buying the black gifts (at the cheaper price) plus the total cost of buying the white gifts, and I submitted my code for testing...
And...??????
...
It worked!!! ????????
But... it failed in two tests... ????
At that moment, I felt frustrated because, in my head, the core issue seemed to be the simple comparison between the current gift cost and the cost of the opposite gift plus the exchange price.
After a few minutes thinking about some alternative logic...
I started to wonder: Why did the code work for all the test cases, but only in two tests, it returned the wrong answer?
There had to be something different about the inputs in test cases eleven and twelve, right?
So, I opened test case twelve to inspect the input data, and... Bingo:
As soon as I saw this input data, I realized?I had to use?BigInt?in my code to perform the arithmetic operations on numbers.
As I mentioned at the start of this article, I rarely use BigInt in my daily work, but I had read about it in documentation and knew what it's mainly used for.
Before we see the final solution, let's dive into the main topic...
Finally... What Is BigInt?
To understand BigInt, we first need to take a look at Number.
In JavaScript, Number is a primitive type used to represent both integer and floating-point values. However, it has a limitation—when dealing with "too large" numeric values, it loses accuracy. This happens because JavaScript numbers are only precise up to 15 digits.
So, what are the safe boundaries for number values? JavaScript can tell us:
const num = Number.MAX_SAFE_INTEGER
console.log(num);
// Output: 9007199254740991
That’s the magic number! This value can also be represented as +(2^53?1) on the upper bound and ?(2^53?1) on the lower bound. Any number that exceeds this range loses precision because the Number type rounds it off.
BigInt exists to store and handle very large integer values that exceed the limits of the Number type...
There are two ways to create a BigInt:
// Option 1
const bigInt1 = 9007199254740996n; // Adding "n" at the end of the integer value
console.log(bigInt1);
// Output 9007199254740996n
// Option 2
const bigInt2 = BigInt(9007199254740996); // Using the BigInt function
console.log(bigInt2);
// Output 9007199254740996n
BigInt is also a JavaScript primitive type:
const bigInt2 = BigInt(9007199254740996);
console.log(typeof bigInt2)
// Output 'bigint'
It's similar to Number, but there are key differences. For instance, you cannot use the built-in Math object methods with BigInt values.
However, we can perform arithmetic operations (like addition, subtraction, multiplication, and division) between two BigInt values.
This is another key concept: BigInt operations only work between two BigInt values.
const bigInt1 = 1000n;
const bigInt2 = 3000n;
console.log(bigInt1 + bigInt2);
// Output: 4000n
Mixing BigInt and Number types is not allowed. Here's an example:
const bigInt1 = 1000n;
const num1 = 4;
console.log(bigInt1 + num1);
// Throws an error: Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
But it works if we convert the Number to BigInt:
console.log(bigInt1 + BigInt(num1));
// Output: 1004n
We can compare BigInt values using the standard comparison operators (<, >, >=, <=, ===, etc.).
Here's an example:
const bigInt1 = 1000n;
const bigInt2 = 2000n;
console.log(bigInt1 < bigInt2);
// Output: true
console.log(bigInt1 > bigInt2);
// Output: false
console.log(bigInt1 === bigInt1);
// Output: true
My Code Using BigInt ????
To complete my HackerRank challenge, I transformed the input numbers into BigInt values to handle large integers. Additionally, since we can’t use Math.min with BigInt, I had to manually compare the values using conditional operators. Finally, I converted the result into a string to represent the value properly, removing the BigInt format (n).
Here’s the code:
I submitted my code...
And... ??
...
...
...
...
...
...
It worked!!! ????????
About performance
Handling BigInt values can lead to performance trade-offs compared to Number operations. In my initial code, I realized that not all cases required handling large parameter values. So, I optimized the function to check whether it's necessary to convert the result to BigInt, using the Number.isSafeInteger() method.
Here’s the adjusted code:
With this adjustment, the function is now prepared to handle large numbers, but only when necessary. This ensures the code remains efficient without sacrificing the ability to work with large values when required.
My final thoughts
In this article, we explored some of the key concepts of BigInt. While I didn’t cover every detail, I highly recommend reading the MDN documentation (linked in the references section) to gain a more comprehensive understanding.
The key takeaway here is the importance of being "aware" of the tools and techniques available to us as developers. You don't need to know everything in depth, but knowing that these tools exist and where to find them is crucial. How do you achieve that? By reading documentation, studying other programmers' code, and continuously learning.
I hope this article has helped you in some way. Feel free to share your thoughts in the comments below, and thanks for reading all the way to the end!
References: ????
Analista de Laboratório / Hospital Pequeno Principe
5 个月Parabéns meu mano! Feliz demais por ver o profissional brilhante que você se tornou
Area comercial | Supervisora de Vendas externas | Closer / Account Executive | Inside Sales | B2B l B2C | Inbound | Outbound | Tecnologia | Saas | Spin Selling | Startup | CRM
5 个月Genial, muito orgulho de você!