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----------------

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay