Search code examples
javascriptparseint

why parseInt() in javascript converting "1abc" to 1?


I am trying to understand how parseInt() will work in javascript, my scenarios are

var x = parseInt("123"); console.log(x); // outputs 123

var x = parseInt("1abc"); console.log(x); // outputs 1

var x = parseInt("abc"); console.log(x); // outputs NaN

as of my observation parseInt() converts a string to integer(not really an integer of string like "12sv") when the string begins with number.

but in reality it should return NaN.


Solution

  • From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

    "If the first character cannot be converted to a number, parseInt returns NaN."