Which way of defining a string would you use?
Are there better ways to do this with even more strings?
I want to set abbreviations for a large set of predefined strings.
If style 1:
let stat = str3;
if (stat === "str1") {
stat = "string1";
} else if (stat === "str2") {
stat = "string2";
} else if (stat ==="str3") {
stat = "string3";
} else if (stat === "str4") {
stat = "string4";
} else if (stat === "str5") {
stat = "string5";
}
If style 2: (I think this is the best visually)
let stat = str3;
if (stat === "str1") stat = "string1";
else if (stat === "str2") stat = "string2";
else if (stat === "str3") stat = "string3";
else if (stat === "str4") stat = "string4";
else if (stat === "str5") stat = "string5";
Switch style:
let stat = str3;
switch (stat) {
case "str1":
stat = "string1";
break;
case "str2":
stat = "string2";
break;
case "str3":
stat = "string3";
break;
case "str4":
stat = "string4";
break;
case "str5":
stat = "string5";
break;
}
Put all the data in an object and then just access the values by key.
const dict = {
str1: 'string1',
str2: 'string2'
};
const stat = 'str1';
console.log(dict[stat]);
In my opinion you should use Switch because it's faster than "if" and also if it gets bigger it will be easier to read.
A switch statement might prove to be faster than ifs provided number of cases are good. If there are only few cases, it might not effect the speed in any case. Prefer switch if the number of cases are more than 5 otherwise, you may use if-else too