Search code examples
javascriptparseint

Why Isn't parseInt(str) Returning an Integer?


I'm working through freeCodeCamp's javascript introduction. Here is the prompt: Use parseInt() in the convertToInteger function so it converts the input string str into an integer, and returns it.

Here is what I have now.

function convertToInteger(str) {
var m = parseInt(str);
if (m!=Number) {
  return NaN;
}
  else {
    return m;}
}
convertToInteger("56");

convertToInteger("56") does not return 56. It does return a number, and a string of words does return NaN.

Nothing I have searched has worked (including specifying the radix and a variety of other options). Of all the solutions I've tried, this has the most correct when run, and there is no hint provided for this question.

What am I missing?


Solution

  • This condition:

    if (m!=Number) {
    

    will always be true. parseInt returns a number. Number is a function. (some number) != (some function) will aways be true.¹ If that was meant to be a type check, it would be if (typeof m !== "number") but again, parseInt always returns a number.

    The number parseInt returns can be the NaN ("not a number") value, though, meaning that parseInt couldn't find any parseable digits at the beginning of the string. You can check whether it is by using the global isNaN function (or Number.isNaN). (You can't do it with if (m === NaN), because NaN is weird and not equal to itself.)


    ¹ Unless someone specifically tries to make it false by overriding valueOf on the function to return a number:

    function foo() {
    }
    // Don't do this. :-)
    foo.valueOf = function() {
    	return 42;
    };
    
    console.log(42 != foo); // false
    console.log(42 == foo); // true

    The "will always be true" would be guaranteed if you used !== instead of !=.