2
\$\begingroup\$

I am new to JavaScript and wondered if there is a more streamlined way of writing this code:

var choices = "ABBCD" // A string containing the letters A-D
var total = 0
function calculate() { // Iterate through choices and add to total depending on the letter
 for (var i=0; i<choices.length; i++) {
 if (choices[i]=="A") {
 total+=1;
 } if (choices[i]=="B") {
 total+=2;
 } if (choices[i]=="C") {
 total+=3;
 } if (choices[i]=="D") {
 total+=4;
 }
 }
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 27, 2016 at 18:29
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Good: Use if-elseif

You are calling 4 if statements with your code even if the 1st one is true. These are all mutually exclusive statements so use if-elseif

for (var i=0; i<choices.length; i++) {
 if (choices[i]=="A") {
 total+=1;
 } else if (choices[i]=="B") {
 total+=2;
 } else if (choices[i]=="C") {
 total+=3;
 } else if (choices[i]=="D") {
 total+=4;
 }
}

Better: Use a switch statement

for (var i=0; i<choices.length; i++) {
 switch (choices[i]) {
 case 'A': 
 total += 1;
 break;
 case 'B': 
 total += 2;
 break;
 case 'C': 
 total += 3;
 break;
 case 'D': 
 total += 4;
 break;
 }
}

Best: Convert the character to its numeric equivalent using its ASCII value

for (var i = 0; i < choices.length; i++) {
 //omitted validation that character is a legal value...
 total += choices[i].charCodeAt(0) - 64;
}
answered Sep 27, 2016 at 18:43
\$\endgroup\$
3
  • \$\begingroup\$ Love the idea of using ASCII, really helpful - thanks! \$\endgroup\$ Commented Sep 27, 2016 at 19:05
  • \$\begingroup\$ One more question, why is using the switch statement preferable? \$\endgroup\$ Commented Sep 27, 2016 at 19:07
  • \$\begingroup\$ @ggordon for most people it is easier to read a switch statement rather than a group of if-else statements. You are doing it based off the value in a variable as opposed to multiple conditions so a switch is well suited here. \$\endgroup\$ Commented Sep 27, 2016 at 19:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.