Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

351
Views
javascript, if condition optimization

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')
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

  1. If pathName.toString().split("/")[1] is empty, then set "tr" as default value
  2. Check if lang is any of the standard languages.
const 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')

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!