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

160
Views
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 answers
Answer question

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 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!