Please explain parseInt() function

Hey guys,

I have tried to understand parseInt() function but it is not making sense still. Could someone explain it simply?

I have used this web page to understand,
It said parseInt() " parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems)".


Hey @Rob03, hope your ok.

Parseint basically to convert a string to integer (if the string have a decimal expersion).
Here a quick example:

var text = "test"
var stringNumber = "20"

console.log(parseInt(text)) //should return NaN
console.log(parseInt(stringNumber)) //should return 20

You can read more about here:

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.


Why do you guys set this question with an answer with parseInt() when it appear not to be necessary? See below a comparison your answer with mine:

// Q 28b Javascript) "IOT solution"

var inp = prompt(“Enter a number”);
let num = parseInt(inp);
counter = 0;
while (counter < num) {

// Q 28b Javascript) "My solution"

var program = prompt(“Guess the number”)
while (program != 10) {
var program = prompt(“Guess another number”)
console.log(“You finally guessed the correct nr which is 10”) ;

Hi @FilipGuldhill,

Well, the IOT solution is a better solution because in your code above, you do not have a type check in your condition. != and !== are two different conditions.

When the user types in his answer, it gets recorded as a string. To convert it into a number we use the parseInt() function.

Now, since you used != operator, your condition looks like this
is "10" == 10 ? Javascript returns true. JS tries to convert the 10 implicitly and checks if it’s equal.
is "10" === 10 ? Javascript returns false. Here there is no implicit conversion and it also checks the type.

It is not advisable to skip the type check because it can lead to many bugs.

Hope this clears it out for you. :smile:

1 Like