I want to improve more than one "if and else if". I have the conditions mentioned below, but I'm annoyed because I'm doing too many "repeats". How can I fix this?
const locale = window.location.origin;
const pathName = window.location.pathname;
let lang = pathName.toString().split("/")[1];
if (lang === "")
lang = "tr"
else if (lang === "en")
lang = "en"
else if (lang === "ar")
lang = "ar"
else if (lang !== "tr" || "en" || "ar")
lang = localStorage.getItem('VueAppLanguage')
console.log(lang)
const res = await axios.get(locale + '/' + lang + '/categories')
pathName.toString().split("/")[1] is empty, then set "tr" as default valueconst locale = window.location.origin;
const pathName = window.location.pathname;
let lang = pathName.toString().split("/")[1] || "tr"; // 1
let noStandardLanguage = !["tr","en","ar"].includes(lang); // 2
if (noStandardLanguage)
lang = localStorage.getItem('VueAppLanguage')
console.log(lang)
const res = await axios.get(locale + '/' + lang + '/categories')
You could take a default value and check against known languages.
lang ||= "tr";
if (!['ar', 'en', 'tr'].includes(lang)) lang = localStorage.getItem('VueAppLanguage');
The expression
lang !== "tr" || "en" || "ar"
does not work like intended, because the comparison
lang !== "tr"
checks only the first string, and never the other for comparison.
A value with logical OR || check is the left hand side (lhs) is truthy, like a not empty string, or others (please see link) and takes only the next value if the lhs is falsy, the opposite of truthy.
For comparing a list (here an array) of values, you could take Array#includes.