My first time using switch
and I'm having some trouble returning anything. As a test I'm taking a string and, based on the character that is tested, console logging some string output.
function pairElement(str) {
switch (str) {
case "A":
console.log("some things")
break;
case "G":
console.log("some more things")
break;
}
}
pairElement("ACG");
The cases are of the same value type so I'm not sure what I'm doing wrong here. Any help would be much appreciated.
Your test is not valid based on the values you are handling in your switch statement. You only handle cases for A
and G
but you passed ACG
. Switch had no way to go if any of the cases specified do not match since you also are missing the default case. Your test would be valid if:
function pairElement(str) {
switch (str) {
case "A":
console.log("some things")
break;
case "G":
console.log("some more things")
break;
}
}
pairElement("A"); // some things - valid
pairElement("G"); // some more things - valid
pairElement("ACG"); // switch case and no default - NOT valid
Adding a default would give you:
function pairElement(str) {
switch (str) {
case "A":
console.log("some things")
break;
case "G":
console.log("some more things")
break;
default:
console.log("something ELSE")
}
}
pairElement("A"); // some things - valid
pairElement("G"); // some more things - valid
pairElement("ACG"); // something ELSE - valid
Now there is also the question what exactly did you expect when you tested for a multi character string vs single one. Handling the single chars in your switch kind of eludes to you expecting the string passed to your function to be tested
char by char and if so you need to state that since that changes the question/requirement.
Updating for the scenario where you want char by char:
function pairElement(str) {
str.split('').forEach(function(v) {
switch (v) {
case "A":
console.log("some things")
break;
case "G":
console.log("some more things")
break;
default:
console.log("something ELSE")
}
}
)
}
pairElement("ACG");
// some things
// something ELSE
// some more things
You should add a default
case since you are passing "ACG" which is not of any case. Switches in any programming language needs a matching case.
DEMO
function pairElement(str) {
switch (str) {
case "A":
console.log("some things")
break;
case "G":
console.log("some more things")
break;
default:
console.log("some things + some more things")
}
}
pairElement("ACG");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With