DEV Community

loading...

Discussion on: I've always been using isNaN wrong! (and you?)

Collapse
functional_js profile image
Functional Javascript • Edited

Yes, the NaN is confusing.

//@test
const aTrue = [NaN, undefined, 0 / 0, "0/0", {}, "{}", "[]", v => v, "1234ZZZ56", "asdf"];
const aFalse = [null, 0 / 5, 3, -0, "", "5", [], Infinity, true, false, 1e30, "123.45"];

logForeachParam(isNaN, aTrue);
logForeachParam(isNaN, aFalse);

// throws: BigInt(3145), 3145n; //TypeError: Cannot convert a BigInt value to a number at isNaN

//@test
const aTrue = [NaN, 0 / 0];
const aFalse = [null, undefined, 5 / 0, 3, -0, "", "5", [], Infinity, true, false,
  "0/0", {}, "{}", "[]", v => v, 3145n, 1e30, "1234ZZZ56", "asdf", "123.45", BigInt(3145)];

logForeachParam(Number.isNaN, aTrue);
logForeachParam(Number.isNaN, aFalse);
/**
@func
is a non-decimal number, and not an exponent
integers as strings are true

@param {number} n
@return {boolean}
*/
const isInt = n => (/^\d+$/).test(n)

//@test
const aTrue = [3, -0, BigInt(3145), 3145n, "5"];
const aFalse = [NaN, 0 / 0, null, undefined, 5 / 0, "", [], Infinity, true, false,
  "0/0", {}, "{}", "[]", v => v, 1e30, "1234ZZZ56", "asdf", "123-456", "123.45", 123.45];

logForeachParam(isInt, aTrue);
logForeachParam(isInt, aFalse);
/*
parseInt() vs Number()
*/
l(parseInt("123456-user")); // 123456
l(parseInt("123456user")); // 123456
l(parseInt("1user")); // 1
l(parseInt("r")); // NaN
l(parseInt("5")); // 5

l(Number("123456-user")); //NaN
l(Number("123456user")); //NaN
l(Number("1user")); // NaN
l(Number("r")); // NaN
l(Number("5")); // 5

Forem Open with the Forem app