Need help. Need an arrow function that expects 2 numbers as input (e.g. 1, 2) and returns the sum of the two numbers. If anything other than 2 numbers is passed, return undefined. Not sure where I'm going wrong on this.
const sum = (num1, num2) => {
if((num1.value !== 0)||(num2.value !== 0)){
return undefined
}
return num1 num2
}
console.log(sum(4,4))
Just keeps returning undefined, and doesn't go to finding sum.
CodePudding user response:
Use isNaN
const sum = (num1, num2) => {
if (isNaN(num1) || isNaN(num2)) {
return undefined;
}
return num1 num2;
};
console.log(sum(4, 4));
CodePudding user response:
You are trying to access a submember of a number value, not an object, so you will always get something you don't want to get. This should work better :
const sum = (num1, num2) => {
if(isNaN(num1) || isNaN(num2)){
return undefined
}
return num1 num2
}
console.log(sum(4,4))
You should also look what is isNaN which is a better way to check if you do receive a number or not :) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
CodePudding user response:
I think what are are looking for is something like this.
const sum = (num1, num2) => {
if (typeof(num1) !== "number" || typeof(num2) !== "number")
return "undefined";
return num1 num2;
}