Search code examples
javascriptparseinttypeof

using parseInt on an input field doesnot work


var num1 = parseInt(document.getElementById("num-one").value) ; //'num-one , num-two'is an <input> text field
var num2 = parseInt(document.getElementById("num-two").value) ;
var test = num1 + num2 ;

so when i open Devtools and type in the console :

typeof test
>'number'

but when I log it :

console.log(test)
>NaN

why ?


Solution

  • If you test out

    typeof NaN

    In the browser console, you'll notice it returns "number."

    Looks like one of the inputs you're trying to parseInt with is probably undefined or null as both of those would return NaN

    Here's a resource to explain why NaN is typeof number

    https://javascriptrefined.io/nan-and-typeof-36cd6e2a4e43#.xzui6g25g