DEV Community

Cover image for Cannot understand this Javascript NaN practice problem. Please help in explaining it.
nparekh1979
nparekh1979

Posted on

Cannot understand this Javascript NaN practice problem. Please help in explaining it.

Question: 

Write a function parseFirstInt that takes a string and returns the first integer present in the string. If the string does not contain an integer, you should get NaN.

Example: parseFirstInt('No. 10') should return 10 and parseFirstInt('Babylon') should return NaN.

Answer:

function parseFirstInt(input) {
let inputToParse = input;
for (let i = 0; i < input.length; i++) {
let firstInt = parseInt(inputToParse);
if (!Number.isNaN(firstInt)) {
return firstInt;
}
inputToParse = inputToParse.substr(1);
}
return NaN;
};

Explanation:

we declare a function 'parseFirstInt' 
it has 1 parameter 'input' 
we declare a variable 'inputToParse' 
we initialize it with a value of the input string
we use a 'for loop' to loop over the elements of the input string
we then declare another variable inside the 'for loop' which is 'firstInt'
we initialize its value with the output we get when we run the parseInt method on variable 'inputToParse'  and store them in the firstInt variable
we then open an if else statement 
our condition is plain & simple
if value of 'firstInt' is NaN then we want it to exit the loop and return NaN
if value of 'firstInt' is not NaN then we want it to execute the block of code in the if / else loop 
we keep checking for the first integer by using the loop 


----------------stopped understanding from here----------------

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More