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?
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?
Share Improve this question edited Oct 21, 2015 at 5:49 Tushar 87.3k21 gold badges163 silver badges181 bronze badges asked Oct 21, 2015 at 5:45 user3721335user3721335 514 bronze badges 1- The ma after function is not required – Tushar Commented Oct 21, 2015 at 5:50
4 Answers
Reset to default 6You 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];
}
var TYPES = {
"PLATINUM":"Platinum Customer",
"GOLD":"Gold Customer",
"SILVER":"Silver Customer"
}
function getType(acctType){
return TYPES[acctType];
}
Assuming accType
will always be passed to function.
- Convert the string to first capital and other small case
- Append Customer to it
Code:
return accType[0] + accType.slice(1).toLowerCase() + ' Customer';
Code Explanation:
accType[0]
: Get the first character of the stringaccType.slice(1).toLowerCase()
: Get the string except first character
Try using the switch
block if you are paring 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";
}
}