Maybe I'm asking google all the wrong questions but I scoured the internet and could not find posts similar to my unique problem.
This is a simple coding challenge from FreeCodeCamp: I need to work on the function abTest(a,b) where when a OR b is less than 0, the function will exit with the value of undefined. This is because we run the value a and b through a square root function. And you cannot take the square root of a negative number. Below is the code.
// Setup
function abTest(a, b) {
if (a < 0) {
a = -a;
return undefined;
} else if (b < 0) {
b = -b;
return undefined;
}
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
// Change values below to test your code
abTest(2,2);
This code I used above works fine. However I have to specify that when a or b is < 0, a is assigned -a and b is assigned -b. Why is this necessary? In addition I want to convert this into a Switch statement, but I run into this problem of negative num values. Below are two switch statements I wrote but when using negative num input the abTest(-2,2) or abTest(2,-2) does not return the value undefined.
My First Switch Statement
switch (a,b) {
case a<0 || b<0:
return undefined;
}
switch (a,b) {
case a < 0:
a = -a;
console.log(undefined);
break;
case b < 0:
b = -b;
console.log(undefined);
break;
}
Where is this hole in my logic concerning switch statements and negative num values?
Thank you guys,