Stumbler
Stumbler

Reputation: 2146

why does isNaN always return true

Having some trouble trying to validate strings that are numbers in JS. isNaN in particular seems to be misbehaving.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>No Quirks!</title>
</head>
     <body>
        <h1>JavaScript Test</h1>

        <button onclick="myNanIsTrue()">Is it a number?</button>

        <p id="writeToHTML"></p>

        <script type="text/javascript">
        function myNanIsTrue() {
             var g = parseInt("40000000") + "<br />";
             var n = g;
             if (isNaN(g)){
                  g="moo!";
             }
             n += g + "<br />";
             document.getElementById("writeToHTML").innerHTML = n;
        }
        </script>
     </body>
</html>

Tried a couple of permutations of this but it just doesn't seem to be working. Can anyone see why this isn't working?

Upvotes: 0

Views: 2182

Answers (4)

jimmy jansen
jimmy jansen

Reputation: 647

isNaN means is Not a Number. This means that it is a function to check if your variable is not a number. In your case you are concatenating <br> to your integer, this converts your integer to a String.

/**
 * Created by jjansen on 10-Mar-15 4:38 PM.
 * stackoverflow
 */
var noNumber = parseInt("40000") + "<br>"; //this is now a String
var test = isNaN( noNumber ); //returns true
console.log("noNumber isNaN: " + test);
var number = parseInt("40000"); //this is a integer
test = isNaN( number );
console.log("number isNaN: " + test);


press f12 and copy this code in your console. You can now see the difference

Upvotes: 1

vladzam
vladzam

Reputation: 5908

In your code, the value of g will always be a string due to the way you build it.

Whenever you add up a String and a Number, you will get a new String by concatenating the two values.

Therefore, in your code, isNaN(g) will always return true.

Upvotes: 0

rubikonx9
rubikonx9

Reputation: 1413

You've written:

var g = parseInt("40000000") + "<br />";

Therefore g is a string: '40000000<br />'.

parseInt("40000000") returns an integer, but then you append a string to it. Javascript implicitly converts the numer to a string, then concatenates them.

String's not a number, so isNaN (correctly) returns true.

Upvotes: 3

Alejandro Iv&#225;n
Alejandro Iv&#225;n

Reputation: 4061

Because g is a string (you're concatenating a string, so it will be converted to one).

Upvotes: 0

Related Questions