Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing NaN values for equality in Javascript

I need to compare two numeric values for equality in Javascript. The values may be NaN as well. I've come up with this code:

if (val1 == val2 || isNaN(val1) && isNaN(val2)) ... 

which is working fine, but it looks bloated to me. I would like to make it more concise. Any ideas?

like image 593
GOTO 0 Avatar asked Jan 22 '12 22:01

GOTO 0


People also ask

Can we compare NaN in JavaScript?

Unlike all other possible values in JavaScript, it is not possible to use the equality operators (== and ===) to compare a value against NaN to determine whether the value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false . The isNaN() function provides a convenient equality check against NaN .

How do you check for equality with NaN?

Check for NaN with self-equality In JavaScript, the best way to check for NaN is by checking for self-equality using either of the built-in equality operators, == or === . Because NaN is not equal to itself, NaN != NaN will always return true .

How do you check if a value is equal to NaN in JavaScript?

The isNaN() method returns true if a value is NaN. The isNaN() method converts the value to a number before testing it.

Is == and === same in JavaScript?

The main difference between the == and === operator in javascript is that the == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.


1 Answers

if(val1 == val2 || (isNaN(val1) && isNaN(val2))) 

Nothing to improve. Just add the parentheses to make it clear to everyone.

like image 95
ThiefMaster Avatar answered Oct 05 '22 01:10

ThiefMaster