Vladimirs
Vladimirs

Reputation: 8599

What's the purpose of the Infinity property?

I accidentally faced an Infinity property in JavaScript and wondered where in the world it can be used? Any real life example please.

Upvotes: 1

Views: 1426

Answers (3)

Stefan Falk
Stefan Falk

Reputation: 25387

You can use it if you don't know what the minimum value of an array or also a mathematical-function is like this:

var minimum = Infinity;
var i = 0;

for(i = 0; i < array.length; i++) {

   if(array[i] < minimum) {
     // new minimum found
     minimum = array[i];
   }
}

alert("Minimum: " + minimum);

Upvotes: 4

Qantas 94 Heavy
Qantas 94 Heavy

Reputation: 16020

I'm assuming you're asking about why there's an Infinity global property, not why there's a concept of having infinities in the first place, which is another matter.

It allows easy comparison with the Infinity value itself, where you get it from some arithmetic:

function inv(x) {
  return x * 100000000000;
}

inv(1e999) === Infinity;

This is especially useful as 1 / 0 is not equal to Infinity in mathematics, so it's not obvious that you can use 1 / 0.

If you want a numeric comparison to always return true, and you're using a variable, you can set the variable to Infinity to always force the condition to be true. Take this example:

var a = Infinity; // some number from elsewhere
var arr = [];
function foo(maxLen) {
  if (arr.length < maxLen) arr.push(1);
}

foo(a); // you can't change the function

This could be useful in cases where you can't change the comparison statement used.

Upvotes: 1

VisioN
VisioN

Reputation: 145398

Here is another real life example:

var x = +prompt('Enter x:'),
    y = +prompt('Enter y:'),
    value = Math.pow(x, y);

if (value === Infinity || value === -Infinity) {
    console.log('The value is too large!');
}

As an example, if the entered values are 1e100 and 100, the power method returns Infinity.

Upvotes: 2

Related Questions