Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

348
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda