-2

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;
  }
  
My Second Switch Statement

  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,

jaysonder
  • 377
  • 4
  • 12
  • 1
    `switch(a, b)` ignores `a` and only checks `b` because `,` is the comma operator and `switch` is not to be used as a function. There can be only one variable there. Also `case`s don’t work like `if` statements; you can’t put conditions there, you need to put values there. – Sebastian Simon Jul 05 '16 at 21:27
  • 2
    There’s no reason to use a `switch` for this. `if (a < 0 || b < 0) return undefined;`. – Ry- Jul 05 '16 at 21:31
  • Ok, but concerning the logic behind the if and else statement. Why and where is my negative num input being converted back to a positive num? Or is the nature of the language and I will have to always assign a number below 0 as negative? – jaysonder Jul 05 '16 at 21:33

1 Answers1

0

There should be no need to convert a = -a unless there is something wrong with freecodecamp. Just returning the value of undefined would/should produce the exact same result as changing a variable and then still returning undefined. To simplify your code you could also combine the if and else if statements like so

function abTest(a, b) {

if (a < 0 || b < 0){
  return undefined;
} else {
  return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
 }
}

hope this helps