Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
Beginner question: returning number value from string

If I give a value to firstParam as 'Ten' or '10' is there some way I can make the program return a number value to the function?

const sum = (firstParam, secondParam) => {
  if (firstParam === Number(firstParam) && secondParam === Number(secondParam))
    return (firstParam - secondParam)
  else
    return ('Invalid argument(s)')
}

console.log(sum(1,1))

EDIT

I have tried many different ways changing the firstParam to Number.firstParam, when i get close i miss out on the correct return statements

const sum = (firstParam, secondParam) =>{
firstParam = Number.firstParam
if (firstParam === Number(firstParam) && secondParam === Number(secondParam) )
return (firstParam - secondParam); 
else 
return ('Invalid argument(s)')
}
console.log(sum(1,1))
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you provide a number in form of string. for example '10'.

You can parse it into Number and then return the sum as shown below.

Example when both arguments are correct.

const sum = (firstParam, secondParam) =>{
  let sum = Number(firstParam)+Number(secondParam);
  return Number(sum)?sum:"Invalid argument(s)";
}

console.log(sum('10','1'))

Example when anyone of the argument is incorrect.

const sum = (firstParam, secondParam) =>{
  let sum = Number(firstParam)+Number(secondParam);
  return Number(sum)?sum:"Invalid argument(s)";
}

console.log(sum('ten','1'))

about 4 years ago · Juan Pablo Isaza Report

0

You need to check the type of the arguments before trying to convert them to a number:

const sum = (firstParam, secondParam) => {
  // If both are numbers everything is ok
  if (typeof firstParam === 'number' && typeof secondParam ===         'number' ) {
    return (firstParam - secondParam);
  }
 
 
  // If are stingified numebrs we convert them
  const firstParamInNumber = parseFloat(firstParam)
  const secondParamInNumber = parseFloat(secondParam)
  
  return isNaN(firstParamInNumber) || isNaN(secondParamInNumber) ? 'Invalid argument(s)' : firstParamInNumber - secondParamInNumber
}

console.log(sum(1,'1'))
console.log(sum(1,1))
console.log(sum(1,'wrong param'))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!