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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments