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

2019-09-07 22:34发布

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.

2条回答
放荡不羁爱自由
2楼-- · 2019-09-07 23:17

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

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

查看更多
混吃等死
3楼-- · 2019-09-07 23:29

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.

查看更多
登录 后发表回答