2

I am just a newbie in javascript, this is how i am writing if condition in a javascript,

function setAccType(accType) {
    if (accType == "PLATINUM") {
        return "Platinum Customer";
    } else if (accType == "GOLD") {
        return "Gold Customer";
    } else if (accType == "SILVER") {
        return "Silver Customer";
    }
},

Is there a better way to do it?

1
  • The comma after function is not required Commented Oct 21, 2015 at 5:50

4 Answers 4

6

You can use an object as a map:

function setAccType(accType){
  var map = {
    PLATINUM: 'Platinum Customer',
    GOLD: 'Gold Customer',
    SILVER: 'Silver Customer'
  }

  return map[accType];
}

Or as @Tushar pointed out:

var accountTypeMap = {
  PLATINUM: 'Platinum Customer',
  GOLD: 'Gold Customer',
  SILVER: 'Silver Customer'
}

function setAccType(accType){  
  return accountTypeMap[accType];
}
Sign up to request clarification or add additional context in comments.

1 Comment

map can be moved outside of the function
2

var TYPES = {
  "PLATINUM":"Platinum Customer",
  "GOLD":"Gold Customer",
  "SILVER":"Silver Customer"
}

function getType(acctType){
    return TYPES[acctType];
}

Comments

2

Assuming accType will always be passed to function.

  1. Convert the string to first capital and other small case
  2. Append Customer to it

Code:

return accType[0] + accType.slice(1).toLowerCase() + ' Customer';

Code Explanation:

  1. accType[0]: Get the first character of the string
  2. accType.slice(1).toLowerCase(): Get the string except first character

Comments

1

Try using the switch block if you are comparing the same variable against different values and having different things happen in different cases:

function setAccType(accType){
    switch(accType) {
        case "PLATINUM" :
            return "Platinum Customer";
        case "GOLD":
            return "Gold Customer";
        case "SILVER":
            return "Silver Customer";
     }
 }

Comments

Your Answer

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.