0

I am trying to convert the following if, else if, else to a switch statement.

    if(zipValue === "") {
    setErrorFor(zip, 'Please enter a zip code');
} else if (!isZip(zipValue)) {
    setErrorFor(zip, 'Not a valid Aust zip code');
} else {
    setSuccessFor(zip);
}

So far I have tried:

switch (zipValue) {
case "":
setErrorFor(zip, 'Please enter a zip code');
break;
case !isZip(zipValue): //can't get this working
setErrorFor(zip, 'Not a valid Aust zip code');
break;
default:
setSuccessFor(zip);
break;

}

the function isZip checks against a regex as shown here:

function isZip(zip) {
 return /^[0-9]{4}$/.test(zip);
 }

The original if, else if, else is working I just want to learn more about using a switch statement and make my code cleaner. Thank you.

PS after posting this I now see the irony that the switch statement is using more lines of code.

caston
  • 159
  • 12
  • 1
    `switch` compares the value of the supplied expression against the case values using a strict comparison (===), here you are comparing against a string in the first case and a boolean in the second so one of them will never match depending on the type of the initial `zipValue`. – pilchard Nov 08 '20 at 02:44
  • I could try something like ternary with conditional chains. – caston Nov 08 '20 at 02:53
  • 1
    Yes, you can try ternary where you return a value instead of boolean for comparison with the zipValue from the switch. Then it'll work. – Link Nov 08 '20 at 02:58
  • I found this about using daisy chained ternary: https://stackoverflow.com/a/49762262/12822663 I have already used one ternary in my program as follows: !terms.checked ? setErrorFor(terms, 'Please agree to the terms') : setSuccessFor(terms); – caston Nov 08 '20 at 03:03
  • 2
    Why are you trying to change this code? The code is already in a clear and readable form. You seem to be deliberately butchering it... why? – Niet the Dark Absol Nov 08 '20 at 03:04
  • Sometimes to have to break something that is working in order to learn more. – caston Nov 08 '20 at 03:05

1 Answers1

1

The value in the case statement for !isZip(zipValue) is always going to return a boolean. I’m guessing that zipValue will always be a string. Therefore that case statement will never be run since you’re comparing two values of two different data types. So if someone inputs a zip code let’s say 12345, then when it gets to that case block it will return false. And 12345 does not equal false

Coder365
  • 26
  • 2