Why is undefined == undefined but NaN != NaN? [duplicate] - javascript

This question already has answers here:
What is the rationale for all comparisons returning false for IEEE754 NaN values?
(12 answers)
Closed 8 years ago.
I am wondering why undefined == undefined but NaN != NaN.

Because that's how it is defined in both the Abstract Equality Comparison Algorithm, and the Strict Equality Comparison Algorithm.
If either operand to == or === is NaN, it returns false.
Abstract
If Type(x) is Number, then
If x is NaN, return false.
If y is NaN, return false.
If x is the same Number value as y, return true.
If x is +0 and y is −0, return true.
If x is −0 and y is +0, return true.
Return false.
EDIT: The motivation for the unequal comparison as noted by #CMS is compliance with the IEEE 754 standard.
From the Wikipedia link provided in the comment below:
...The normal comparison operations however treat NaNs as unordered and compare −0 and +0 as equal. The totalOrder predicate will order these cases, and it also distinguishes between different representations of NaNs and between the same decimal floating point number encoded in different ways.

Because Math.sqrt(-5) !== Math.sqrt(-6).

Not sure why it is like this, but in order to check if a certain statement or variable is a NaN, you should use the isNaN method

I would assume because the IEEE standard allows for more than one representation of NaN. Not all NaNs are equal to each other...

The reasoning is that the creators wanted x == x returning false to mean that x is NaN, so NaN == NaN has to return false to be consistent.

Related

When is "value !== value" ever true? [duplicate]

This question already has answers here:
What is the rationale for all comparisons returning false for IEEE754 NaN values?
(12 answers)
Closed 5 years ago.
Why does NaN === NaN return false in Javascript?
> undefined === undefined
true
> NaN === NaN
false
> a = NaN
NaN
> a === a
false
On the documentation page I see this:
Testing against NaN
Equality operator (== and ===) cannot be used to test a value against NaN. Use isNaN instead.
Is there any reference that answers to the question? It would be welcome.
Strict answer: Because the JS spec says so:
If Type(x) is Number, then
If x is NaN, return false.
If y is NaN, return false.
Useful answer: The IEEE 754 spec for floating-point numbers (which is used by all languages for floating-point) says that NaNs are never equal.
This behaviour is specified by the IEEE-754 standard (which the JavaScript spec follows in this respect).
For an extended discussion, see What is the rationale for all comparisons returning false for IEEE754 NaN values?
Although either side of NaN===NaN contains the same value and their type is Number but they are not same. According to ECMA-262, either side of == or === contains NaN then it will result false value.
you may find a details rules in here-
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

Number function is considering -0 as 0 in javascript [duplicate]

Reading through the ECMAScript 5.1 specification, +0 and -0 are distinguished.
Why then does +0 === -0 evaluate to true?
JavaScript uses IEEE 754 standard to represent numbers. From Wikipedia:
Signed zero is zero with an associated sign. In ordinary arithmetic, −0 = +0 = 0. However, in computing, some number representations allow for the existence of two zeros, often denoted by −0 (negative zero) and +0 (positive zero). This occurs in some signed number representations for integers, and in most floating point number representations. The number 0 is usually encoded as +0, but can be represented by either +0 or −0.
The IEEE 754 standard for floating point arithmetic (presently used by most computers and programming languages that support floating point numbers) requires both +0 and −0. The zeroes can be considered as a variant of the extended real number line such that 1/−0 = −∞ and 1/+0 = +∞, division by zero is only undefined for ±0/±0 and ±∞/±∞.
The article contains further information about the different representations.
So this is the reason why, technically, both zeros have to be distinguished.
However, +0 === -0 evaluates to true. Why is that (...) ?
This behaviour is explicitly defined in section 11.9.6, the Strict Equality Comparison Algorithm (emphasis partly mine):
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
(...)
If Type(x) is Number, then
If x is NaN, return false.
If y is NaN, return false.
If x is the same Number value as y, return true.
If x is +0 and y is −0, return true.
If x is −0 and y is +0, return true.
Return false.
(...)
(The same holds for +0 == -0 btw.)
It seems logically to treat +0 and -0 as equal. Otherwise we would have to take this into account in our code and I, personally, don't want to do that ;)
Note:
ES2015 introduces a new comparison method, Object.is. Object.is explicitly distinguishes between -0 and +0:
Object.is(-0, +0); // false
I'll add this as an answer because I overlooked #user113716's comment.
You can test for -0 by doing this:
function isMinusZero(value) {
return 1/value === -Infinity;
}
isMinusZero(0); // false
isMinusZero(-0); // true
I just came across an example where +0 and -0 behave very differently indeed:
Math.atan2(0, 0); //returns 0
Math.atan2(0, -0); //returns Pi
Be careful: even when using Math.round on a negative number like -0.0001, it will actually be -0 and can screw up some subsequent calculations as shown above.
Quick and dirty way to fix this is to do smth like:
if (x==0) x=0;
or just:
x+=0;
This converts the number to +0 in case it was -0.
2021's answer
Are +0 and -0 the same?
Short answer: Depending on what comparison operator you use.
Long answer:
Basically, We've had 4 comparison types until now:
‘loose’ equality
console.log(+0 == -0); // true
‘strict’ equality
console.log(+0 === -0); // true
‘Same-value’ equality (ES2015's Object.is)
console.log(Object.is(+0, -0)); // false
‘Same-value-zero’ equality (ES2016)
console.log([+0].includes(-0)); // true
As a result, just Object.is(+0, -0) makes difference with the other ones.
const x = +0, y = -0; // true -> using ‘loose’ equality
console.log(x === y); // true -> using ‘strict’ equality
console.log([x].indexOf(y)); // 0 (true) -> using ‘strict’ equality
console.log(Object.is(x, y)); // false -> using ‘Same-value’ equality
console.log([x].includes(y)); // true -> using ‘Same-value-zero’ equality
In the IEEE 754 standard used to represent the Number type in JavaScript, the sign is represented by a bit (a 1 indicates a negative number).
As a result, there exists both a negative and a positive value for each representable number, including 0.
This is why both -0 and +0 exist.
Answering the original title Are +0 and -0 the same?:
brainslugs83 (in comments of answer by Spudley) pointed out an important case in which +0 and -0 in JS are not the same - implemented as function:
var sign = function(x) {
return 1 / x === 1 / Math.abs(x);
}
This will, other than the standard Math.sign return the correct sign of +0 and -0.
We can use Object.is to distinguish +0 and -0, and one more thing, NaN==NaN.
Object.is(+0,-0) //false
Object.is(NaN,NaN) //true
I'd blame it on the Strict Equality Comparison method ( '===' ).
Look at section 4d
see 7.2.13 Strict Equality Comparison on the specification
If you need sign function that supports -0 and +0:
var sign = x => 1/x > 0 ? +1 : -1;
It acts as Math.sign, except that sign(0) returns 1 and sign(-0) returns -1.
There are two possible values (bit representations) for 0. This is not unique. Especially in floating point numbers this can occur. That is because floating point numbers are actually stored as a kind of formula.
Integers can be stored in separate ways too. You can have a numeric value with an additional sign-bit, so in a 16 bit space, you can store a 15 bit integer value and a sign-bit. In this representation, the value 1000 (hex) and 0000 both are 0, but one of them is +0 and the other is -0.
This could be avoided by subtracting 1 from the integer value so it ranged from -1 to -2^16, but this would be inconvenient.
A more common approach is to store integers in 'two complements', but apparently ECMAscript has chosen not to. In this method numbers range from 0000 to 7FFF positive. Negative numbers start at FFFF (-1) to 8000.
Of course, the same rules apply to larger integers too, but I don't want my F to wear out. ;)
Wikipedia has a good article to explain this phenomenon: http://en.wikipedia.org/wiki/Signed_zero
In brief, it both +0 and -0 are defined in the IEEE floating point specifications. Both of them are technically distinct from 0 without a sign, which is an integer, but in practice they all evaluate to zero, so the distinction can be ignored for all practical purposes.

How Number.Nan works in this function? [duplicate]

This question already has answers here:
What is the rationale for all comparisons returning false for IEEE754 NaN values?
(12 answers)
Closed 6 years ago.
Why does NaN === NaN return false in Javascript?
> undefined === undefined
true
> NaN === NaN
false
> a = NaN
NaN
> a === a
false
On the documentation page I see this:
Testing against NaN
Equality operator (== and ===) cannot be used to test a value against NaN. Use isNaN instead.
Is there any reference that answers to the question? It would be welcome.
Strict answer: Because the JS spec says so:
If Type(x) is Number, then
If x is NaN, return false.
If y is NaN, return false.
Useful answer: The IEEE 754 spec for floating-point numbers (which is used by all languages for floating-point) says that NaNs are never equal.
This behaviour is specified by the IEEE-754 standard (which the JavaScript spec follows in this respect).
For an extended discussion, see What is the rationale for all comparisons returning false for IEEE754 NaN values?
Although either side of NaN===NaN contains the same value and their type is Number but they are not same. According to ECMA-262, either side of == or === contains NaN then it will result false value.
you may find a details rules in here-
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

Why this JavaScript includes() feature make sense? [duplicate]

This question already has answers here:
Why does [NaN].includes(NaN) return true in JavaScript?
(5 answers)
Closed 24 days ago.
I'm learning about includes() feature, and I found this code
[NaN].includes(NaN) //True
But
NaN === NaN // False
Why this is posible?
Using equality NaN === NaN and using includes [NaN].includes(NaN) are basically asking two different questions:
Equality - are this things that have the same name are actually equal?
NaN is an amorphic entity, which describes the concept of not being a numeric value, and doesn't actually have a value you can compare. Equality uses the Strict Equality Comparison, and defines that a comparison x === y with NaN on any side of the equation is always false:
a. If x is NaN, return false.
b. If y is NaN, return false.
Includes - do I have something with that "name" in the array?
However, to search for a NaN in an array, and to keep the to Array#includes signature of passing only one param, and not a callback, we need a way to "name" what we are searching for. To make that possible, ccording to the Array#includes definition in the ECMAScript 2016 (ECMA-262) docs:
The includes method intentionally differs from the similar indexOf
method in two ways. First, it uses the SameValueZero algorithm,
instead of Strict Equality Comparison, allowing it to detect NaN
array elements. Second, it does not skip missing array elements,
instead treating them as undefined.
The definition of SameValueZero(x, y) states that when comparing:
If x is NaN and y is NaN, return true.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function.
[ NaN ].includes(NaN) what this does is to check if NaN is in the [ ].
NaN === NaN and NaN == NaN will still return the same value which is false. What you just have to know is that the includes methods checks if a value is the array it is been called on. Behind the hood i think the includes Array method does it's checks using typeof()
typeof(NaN) // number
[ NaN ].includes(NaN) // true
typeof("1") // string
[ 1 ].includes("1") // false
typeof(1) // number
[ 1 ].includes(1) // true
this is according to the SameValueZero Algorithm that the includes method uses. Internally it checks the type of the value

Why is IsNaN(x) different from x == NaN where x = NaN [duplicate]

This question already has answers here:
What is the rationale for all comparisons returning false for IEEE754 NaN values?
(12 answers)
Closed 10 years ago.
Why are these two different?
var x = NaN; //e.g. Number("e");
alert(isNaN(x)); //true (good)
alert(x == NaN); //false (bad)
Nothing is equal to NaN. Any comparison will always be false.
In both the strict and abstract comparison algorithms, if the types are the same, and either operand is NaN, the result will be false.
If Type(x) is Number, then
If x is NaN, return false.
If y is NaN, return false.
In the abstract algorithm, if the types are different, and a NaN is one of the operands, then the other operand will ultimately be coerced to a number, and will bring us back to the scenario above.
The equality and inequality predicates are non-signaling so x = x returning false can be used to test if x is a quiet NaN.
Source
This is the rule defined in IEEE 754 so full compliance with the specification requires this behavior.
The following operations return NaN
The divisions 0/0, ∞/∞, ∞/−∞, −∞/∞, and −∞/−∞
The multiplications 0×∞ and 0×−∞
The power 1^∞
The additions ∞ + (−∞), (−∞) + ∞ and equivalent subtractions.
Real operations with complex results:
The square root of a negative number
The logarithm of a negative number
The tangent of an odd multiple of 90 degrees (or π/2 radians)
The inverse sine or cosine of a number which is less than −1 or greater than +1.
The following operations return values for numeric operations. Hence typeof Nan is a number. NaN is an undefined number in mathematical terms. ∞ + (-∞) is not equal to ∞ + (-∞). But we get that NaN is typeof number because it results from a numeric operation.
From wiki:

Categories