Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement not returning values

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.

like image 878
Pbculley Avatar asked Dec 10 '22 05:12

Pbculley


2 Answers

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
like image 122
Akrion Avatar answered Dec 15 '22 00:12

Akrion


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"); 

 
like image 44
Sajeetharan Avatar answered Dec 14 '22 23:12

Sajeetharan