Why is isFinite(undefined) != isFinite(null)?

2019-09-07 23:11发布

问题:

Why is the value for undefined considered Finite in javascript while null is not?

This is a very basic question, which has thwarted my googlefoo (too much noise).

isFinite(undefined); // false
isFinite(null); // true

I do not understand as I would expect null and undefined to be handled in the same manner.

回答1:

This is because Number(null) === 0.

http://es5.github.io/#x9.3



回答2:

isFinite (number)

Returns false if the argument coerces to NaN, +∞, or −∞, and otherwise returns true.

isFinite convert input using Number() and:

Number(undefined); //== NaN
Number(null); //== 0

that is the reason undefined is false and null is true for isFinite.

If you try:

isFinite(!undefined); // true

because undefined is NaN and on negating it it converted to 1 which is finite.