parseInt function –
For example –
parseInt(“100”) ; // 100
For more information on parseInt function.
First we declare a variable year using let keyword and assign “20 Years” string to it.
let year = “20 Years”;
In the next, we declare another variable yearAfter using let and assign “Years 20” to it.
let yearAfter = “Years 20“;
Now, here is the main part of what would happen with yearAfter variable when it passes to parseInt function.
Let’s find out the answer for it.
Now, you know the answer is NaN but confused too. That why the first console log gives 20 in which year variable is passed which contains “20 Years” as a string.
But in yearAfter variable, “Years 20” is stored. Then why is give NaN
Let me explain it, in simple terms. When parseInt function change the string to number then first it look for first character of the string.
If the first character can not be converted to number then it always return NaN.
So, when “20 Years” passed to it first character is 2 which can be converted to a number. But in “Years 20” first character is Y which can’t be converted to number.
That’s why we get an answer of NaN
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – What actually optional chaining operator doing with object
- JS Quiz – What value should return when adding multiple arrays
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.