Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does "Infinity==Infinity" in JavaScript becomes true?

Tags:

javascript

As far as I know, in math both Infinity and NaN are vague values. as all of us know:

console.log(NaN == NaN); //-> false

while

console.log(Infinity==Infinity); //-> true

I'm wondering why the result of the second code is true. I'm expecting that the result of the second one, should be false, but it's not.

Could you please help me out. I'd really appreciate it. Thanks.

like image 940
reza Avatar asked Aug 31 '26 07:08

reza


2 Answers

This is why:

NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN

The initial value of Infinity is Number.POSITIVE_INFINITY. The value Infinity (positive infinity) is greater than any other number. This value behaves mathematically like infinity; for example, any positive number multiplied by Infinity is Infinity, and anything divided by Infinity is 0.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity

What you also might be interested in is using the isFinite method of Number:

Number.isFinite(Infinity);  // false
Number.isFinite(NaN);       // false

Read up on Number.isFinite(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite

like image 160
manonthemat Avatar answered Sep 02 '26 21:09

manonthemat


In addition to the other answers: Because the spec says so.

NaN is the only value in JavaScript that is not equal to itself:

A reliable way for ECMAScript code to test if a value X is a NaN is an expression of the form X !== X. The result will be true if and only if X is a NaN.

http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.4

like image 38
TimoStaudinger Avatar answered Sep 02 '26 20:09

TimoStaudinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!