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

158
Visualizações
Can we simplified this code? show = typeof show == 'undefined' ? undefined : !show
function myToggle(show) {
    //...bunch of codes here...

    show = typeof show == 'undefined' ? undefined : !show
    $(el).toggleClass('d-none', show )
}

In above function, show will be inverted (boolean) only if its defined, then pass into jQuery's toggleClass(). d-none is a Bootstrap class to hide element.

So that when:

myToggle()    //this will toggle class d-none to the element
myToggle(1)   //this will remove class d-none from the element
myToggle(0)   //this will give class d-none to the element

So my question, can we simplified this code?

show = typeof show == 'undefined' ? undefined : !show
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Let's start with the fact that this should be ===, not just ==. You almost never want == in JS (it's not Java or C++, always use === unless you actually know why you shouldn't). With that, you don't need a typeof check: just check whether your var is undefined, directly.

show = show === undefined? show : !show;

However, this ignores how jQuery's .toggleClass() even works. It doesn't take "true or false or undefined" as second argument, it takes a boolean, and "show" is pretty explicit in its intention, so the real simplication is the most obvious one:

show = !!show;
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