Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize if condition javascript

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?

like image 784
user3721335 Avatar asked Jun 04 '26 17:06

user3721335


2 Answers

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];
}
like image 65
CD.. Avatar answered Jun 06 '26 06:06

CD..


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

function getType(acctType){
    return TYPES[acctType];
}
like image 27
Shanimal Avatar answered Jun 06 '26 07:06

Shanimal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!