Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

349
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda