connexo
connexo

Reputation: 56754

Why does Number(null) return 0, and parseFloat(null) return NaN?

I'm trying to write a helper function that will cast a String coming from an <input type="text" /> to a Number.

As I wasn't sure whether to use parseFloat(str) or Number(str) I doublechecked how they handle potentially problematic arguments.

See:

console.log(Number(null)); // 0
console.log(parseFloat(null)); // NaN
console.log(parseInt(null)); // NaN
console.log(isNaN(null)); // false

Both parseFloat and parseInt return NaN, whereas Number returns 0. Number seems more coherent here with isNaN(null).

Why is that?

Upvotes: 2

Views: 5266

Answers (4)

Abhishek Nagekar
Abhishek Nagekar

Reputation: 124

Number constructor tries to coerce the argument to number. So empty string '', false, null and all falsy values become 0.

Similarly, Number(true) will return 1. Number('some string') will be NaN as 'some string' cannot be converted to a number.

Note that as pointed out in the comments, Number(undefined) is NaN and not 0 in arithmetic operations. (Read here https://codeburst.io/understanding-null-undefined-and-nan-b603cb74b44c)

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

Upvotes: 3

georg
georg

Reputation: 214949

  • parseInt/Float convert their argument to a string, read it char by char from the left and try to make a number from what they've found. Since String(null) is "null" and a decimal number cannot start with "n", parseInt(null) will be NaN. If you provide a different base, where n, u and l are digits, the result will be different:

console.log(parseInt(null, 32))

  • Number converts its argument as a whole into a number. Number(null) returns +0 because the ECMA committee wants it to: http://www.ecma-international.org/ecma-262/7.0/#sec-tonumber . This is probably for historical reasons.

  • global isNaN (not to confuse with Number.isNaN) applies Number to its argument and returns true if the result is NaN. Since Number(null) is +0, isNaN(null) is false.

Hope this sheds some light...

Upvotes: 2

connexo
connexo

Reputation: 56754

The reason seems to be quite subtle with how parseInt and parseFloat work:

If the argument passed to parseInt/parseFloat is not a String (which null isn't), then it calls toString(null) which returns "[object Undefined]".

If the first character cannot be converted to a number, parseInt returns NaN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Upvotes: 0

Diogenis Siganos
Diogenis Siganos

Reputation: 797

NaN stands for "Not a Number". ParseFloat and ParseInt return real numbers and integers, so this is like an error returned by the function. Number(), on the other hand, represents the object's value. For instance, Number(false) will output 0.

Upvotes: 0

Related Questions