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