JavaScript Interview Question: Infinity  and negative infinity

JavaScript Interview Question: Infinity and negative infinity

Are you a JavaScript developer who has come across the term "infinity" and wondered what it means and when it is used in the language? Look no further, as this article is going to give you a detailed understanding of infinity in JavaScript.

Infinity is a special integer value in JavaScript that is greater than any value. There are two types of infinity: positive infinity and negative infinity. In this article, we will explore both types of infinity and see when they are used.

Positive Infinity

Positive infinity is the highest possible value available in JavaScript. To use positive infinity, you can use the constant Infinity. Let's try an example:

console.log(Number.POSITIVE_INFINITY); // Infinity

As you can see, the output of this code is Infinity means that the value is greater than any number that JavaScript can handle.

Negative Infinity

Negative infinity is the opposite of positive infinity. It is the lowest possible value available in JavaScript. To use negative infinity, you can use the constant -Infinity. Let's try an example:

console.log(Number.NEGATIVE_INFINITY); // -Infinity

As you can see, the output of this code is -Infinity, which means that the value is smaller than any number that JavaScript can handle.

When is Infinity Used?

In JavaScript, numbers are stored in 64-bit format. If a value is too large to fit in 64 bits, it will return infinity. This means that any value that cannot fit in 64 bits will be considered infinite.

console.log(10 ** 1000); // Infinity

The exponentiation operator ** performs the calculation of raising the first operand to the power of the second operand and returns the result. This operator is similar in functionality to the Math.pow() method.

As you can see, the output of this code is Infinity. This is because the value 10 ** 1000 is too large to be stored in 64 bits, so it is considered infinite.

Conclusion

In this article, we have explored the concept of infinity in JavaScript. We have seen that there are two types of infinity: positive infinity and negative infinity. We have also seen that numbers in JavaScript are stored in 64-bit format, and if a value is too large to fit in 64 bits, it will return infinity. With this knowledge, you can now confidently use infinity in your JavaScript code.


The content of this blog post was inspired by the JavaScript - Marathon Interview Questions Series 2023 course on Udemy

(https://www.udemy.com/course/javascript-marathon-interview-questions-series/)