Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

180
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda