Javascript nan is false

Why NaN === NaN returns false in JavaScript ?!

When people start exploring topics about JavaScript they get to feel a little weird sometimes and they also start to wonder why the heck do JavaScript act in such a manner, there have been even Github Repos like You Don’t Know JS that explains how JavaScript works and so. Today I wanted to explain a gotcha topic that people usually post memes about and hate on JavaScript because of such a topic ( Which I kinda understand why they do so ), I will be explaining why NaN === NaN results in a Falsy expression. Let us get started with some basics first.

What is the difference between == and ===

Whenever we compare two variables using the double equal operator we compare them using only their values, meaning if a variable A contains some value and variable B contains some other value and we did A == B what will happen is that JavaScript will check their current values and return true if they are equal. but what if we did something like this: «1» == 1 , what would be the result of such expression? A normal person with some logical understanding would definitely guess that the output would be false because we are comparing a string to a number even if they have the same characters. What will actually happen is that this output will be expressed as true . Why is that? When we use the double equal operator JavaScript will attempt to convert and compare operands of different types, meaning that they both would be converted to the same type and in case of comparing a number to a string JavaScript will try and convert the string to a number type like this: Number(«1») == 1 which will output in that case true . What if we have a case in which we actually want to compare the types of the variables we have and then compare their values without attempting any conversion?
In that case, using the triple equal operators or the Strict equality would come in handy, what the strict equality operator simply does is checking if the operands are of the same type and then checks if they have the same value or not.

let a = "1"; let b = 1; console.log(a == b) // true; console.log(a === b) // false; 

We could simply imagine that JavaScript under the hood does something like this when using the strict equality:

let a = "1"; let b = 1; console.log(typeof a == typeof b && a == b) // in case of doing a === b; 

What is NaN

So basically NaN is simply a global object that describes what a not number is or whenever we have a variable that we are attempting to convert to a number and we fail it simply gives us NaN like this:

let a = "hello world"; let convertedToNumber = Number(a); console.log(convertedToNumber); // NaN; 

What is typeof

  • Undefined «undefined»
  • Null «object» (see below)
  • Boolean «boolean»
  • Number «number»
  • BigInt «bigint»
  • String «string»
  • Symbol «symbol»
  • Function object (implements [[Call]] in ECMA-262 terms) «function»
  • object «object»
Читайте также:  How to reverse array python

Whenever typeof is used one of these types would be the result, an example for that would be:

typeof "" // string; typeof 1 // number; typeof function() <> // function; typeof true // boolean; 

Why NaN === NaN returns false ?

And finally, let us get into the core of this article, why when we explained how strict equality works and what is NaN does this expression provide us with a falsy value?

let us simplify the answer by looking into the strict equality comparison algorithm:

let us define the following two operands: x, and y.

according to the JavaScript documentation ( This is a snippet from the docs ), the comparison algorithm works in the following matter:

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.

This means that the algorithm first checks if one of the operands is NaN before even checking their types and if so it will return false anyways.

This may be a weird implementation of the comparison algorithm but there are some workarounds for this, we could use built-in functions like Number.isNaN() to check whether the giving parameter is a NaN or not instead of comparing it with NaN directly

let invalidNumber = Number("asdasdasd"); // NaN; let resultOfNormalComparison = invalidNumber === NaN; // false; let resultOfBuiltInComparison = Number.isNaN(invalidNumber); // true; 

Edit:
This part is being edited after recieving comments about why actually NaN is not equal to NaN from a mathematical prespective, I came accross this answer in stackoverflow and it helped me alot, would recommend it to anyone: answer

Conclusion

You could somehow disagree on the implementation of the comparison algorithm but there are workarounds to check if a given variable or parameter is a NaN or not as shown above.

Источник

Number.isNaN()

The Number.isNaN() static method determines whether the passed value is the number value NaN , and returns false if the input is not of the Number type. It is a more robust version of the original, global isNaN() function.

Try it

Syntax

Parameters

The value to be tested for NaN .

Return value

The boolean value true if the given value is a number with value NaN . Otherwise, false .

Description

The function Number.isNaN() provides a convenient way to check for equality with NaN . Note that you cannot test for equality with NaN using either the == or === operators, because unlike all other value comparisons in JavaScript, these evaluate to false whenever one operand is NaN , even if the other operand is also NaN .

Since x !== x is only true for NaN among all possible JavaScript values, Number.isNaN(x) can also be replaced with a test for x !== x , despite the latter being less readable.

As opposed to the global isNaN() function, the Number.isNaN() method doesn’t force-convert the parameter to a number. This makes it safe to pass values that would normally convert to NaN but aren’t actually the same value as NaN . This also means that only values of the Number type that are also NaN return true .

Examples

Using isNaN()

.isNaN(NaN); // true Number.isNaN(Number.NaN); // true Number.isNaN(0 / 0); // true Number.isNaN(37); // false 

Difference between Number.isNaN() and global isNaN()

Number.isNaN() doesn’t attempt to convert the parameter to a number, so non-numbers always return false . The following are all false :

.isNaN("NaN"); Number.isNaN(undefined); Number.isNaN(>); Number.isNaN("blabla"); Number.isNaN(true); Number.isNaN(null); Number.isNaN("37"); Number.isNaN("37.37"); Number.isNaN(""); Number.isNaN(" "); 

The global isNaN() coerces its parameter to a number:

isNaN("NaN"); // true isNaN(undefined); // true isNaN(>); // true isNaN("blabla"); // true isNaN(true); // false, this is coerced to 1 isNaN(null); // false, this is coerced to 0 isNaN("37"); // false, this is coerced to 37 isNaN("37.37"); // false, this is coerced to 37.37 isNaN(""); // false, this is coerced to 0 isNaN(" "); // false, this is coerced to 0 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

How is NaN converted to Boolean in JavaScript?

In this article, we will learn how to convert NaN to Boolean. NaN in JavaScript means Not a Number, whose type is a Number but actually, it is not a number. To Convert, the NaN to a Boolean we use Multiple methods some of which are discussed below.

  • Using the Boolean() Function
  • Using the !! Operator
  • Using the NOT Operator and isNaN() Method

Using the Boolean() Function

The Boolean function is used to get the Boolean value (True or False) of any variable, condition, or object. To convert the NaN into Boolean we just need to pass the NaN in the Boolean function.

Syntax

Following is the syntax to convert NaN to Boolean:

Here Boolean() function returns false.

Example 1

In this example, we created a variable named bool and passed the NaN inside the Boolean function and stored the returned value to bool, and printed the result.

html> body> p>Convert NaN to Boolean /p> p id ="result">/p> script> let bool = Boolean(NaN) document.getElementById("result").innerHTML += bool +"
"
; document.getElementById("result").innerHTML += typeof bool /script> /body> /html>

Using the !! Operator

The Logical NOT operator followed by another Logical NOT operator is a simple and elegant method to convert the NaN to Boolean. The first logical operator converts the value to the Boolean and another logical operator reverses the value returned by the first operator.

Syntax

Let’s break down the operator into two-part with an example:

Example 2

In this example, we created a variable named x and stored Tutorials point to it and created another variable named x1 in which we stored the value of !x, here the logical operator converts the value to the Boolean and another operator(x2) reverses the result given by the first operator(x1).

html> body> p id ="output">/p> script> var x = "Tutorials Point" var x1 = !x; // false var x2 = !!x; // true document.getElementById("output").innerHTML = x1 + "
"
; document.getElementById("output").innerHTML += x2 /script> /body> /html>

Example 3

In this example, we will convert the NaN to Boolean.

html> body> p>Convert NaN to Boolean/p> p id ="output">/p> script> let bool = !!NaN; document.getElementById("output").innerHTML += bool +"
"
; document.getElementById("output").innerHTML += typeof bool /script> /body> /html>

Using the NOT Operator and isNaN() Method

We can use the NOT operator and isNaN() method to convert NaN to Boolean. The isNaN() method returns true if the value is NaN else false. The isNaN() method converts the value to the number before it tests the value. The NOT(!) operator converts true to false.

Syntax

Here isNaN() returns true as the value is NaN and finally the ! operator converts the true to false.

Example 4

In the example below, we convert NaN to boolean using the isNaN() method. We also test the type of the variable after converting it to boolean.

html> body> p>Convert NaN to Boolean/p> p id ="output">/p> script> let bool = !isNaN(NaN); document.getElementById("output").innerHTML += bool +"
"
; document.getElementById("output").innerHTML += typeof bool /script> /body> /html>

As we have mentioned three methods here are high performance. The Boolean function is widely used by some developers while the !! operator method seems a little non-readable and some developers have no knowledge about it. If we talk about the speed of both of the solutions the !! operator is a little faster than the Boolean function. The third method we discussed is to use the ! operator and isNaN() in combination. It converts the NaN to boolean as false.

Источник

Оцените статью