An arrow function can 'unbloat' your conditional and I would use Number.isNaN()
instead of isNaN()
due to the fact that isNaN()
will try to convert the value to a number.
const areEqual = (a, b) => a === b || (Number.isNaN(a) && Number.isNaN(b));
if (areEqual(val1, val2)) {...}
Using isNaN()
might lead to the following problems:
let val1 = 'a string';
let val2 = undefined;
let val3 = {};
isNaN(val1) && isNaN(val2) && isNaN(val3); // true
Number.isNaN(val1) && Number.isNaN(val2) && Number.isNaN(val3); // false
isNaN(1n); // Uncaught TypeError: Cannot convert a BigInt value to a number
Number.isNaN(1n); // false
Number.isNaN() - JavaScript | MDN
||
and&&
without some parentheses is extremely ugly and confusing. – PsychodiagnosticsNaN
andNaN
are supposed to be unequal for a reason, because, for example,0/0
andparseInt("not a number!")
, while they both evaluate toNaN
, should not be considered equal. – Vlaminck