Ahu Lee Ahu Lee - 2 months ago 10
Javascript Question

Adding a string (with only digits in it) to a number results in a number (according to isNaN) which looks like it should have been a string?

1) Why the 155100 is a number here? Just like 255 would be if

var s = 155;
.

2) Why the 155100 is still a number even if
var n = "100";
?

3) Where and why is
var res
converted to a number?

What am I missing here?



var s = "155";
var n = 100;
var res = s + n;
document.write(res + "<hr>");
if ( isNaN(res) ) {
document.write("It is not a number");
}
if ( !isNaN(res) ) {
document.write("It is a number");
}

<html>
<head>
<title>stackoverflow.com</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>





Thank you so much!

Answer

To your questions:

  1. Why the 155100 is a number here? Just like 255 would be if var s = 155;?

    It is a string, but when passed to isNaN, that function coerces it to a number and then returns whether that coercion resulted in NaN.

  2. Why the 155100 is still a number even if var n = "100";?

    See above. It is not.

  3. Where and why is var res converted to a number?

    It is not -- it remains a string.

But as documented on MDN:

When the argument to the isNaN function is not of type Number, the value is first coerced to a Number.

Notes

To check if a variable is of the Number type:

if (typeof res === 'number') 

To convert a string to a number, one of these:

i = +res;
i = Number(res);

If you want to only check the start of a string, and not fail if any subsequent characters are not numeric (like 123.45abc), then use:

i = parseFloat(res);

If your interest is only in integers, you can use parseInt, preferably with the second argument to indicate the base. Like with parseFloat, it does not return NaN as soon as the first character passes the test:

i = parseInt(res, 10);