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

145
Views
If/else redundant code in ternary operator

This code works fine, but it looks like it could be optimized as it just reverses the ternary order. Any idea how to achieve that?

if ($("#advanced-search-panel").hasClass("hidden")) {
    adv_text.text(adv_text.text() == "Show advanced search" ? "Hide advanced search" : "Show advanced search");
}else{
    adv_text.text(adv_text.text() == "Hide advanced search" ? "Show advanced search" : "Hide advanced search");
}
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Since adv_text.text() only has two possibilities - show and hide - the entire condition

if ($("#advanced-search-painel").hasClass("hidden")) {

is superfluous, because no matter whether the class exists or not, you want to toggle the text from show to hide, or from hide to show, depending on what the text currently is. Your code simplifies to

adv_text.text(
  adv_text.text() == "Show advanced search" ? "Hide advanced search" : "Show advanced search"
);

Another option would be to have an inline element for the part of the text that changes, so that you only have to check and change that.

<div><span class="adv-search-toggle-text">Show</span> advanced search</div>
const span = $('.adv-search-toggle-text');
span.text(span.text() === 'Show' ? 'Hide' : 'Show');

It sounds like the hidden class might have something to do with the text toggling above. If it does, there's a chance you could use CSS rules alone to have Show shown when the hidden class is applied, and Hide shown when the hidden class isn't applied.

about 4 years ago · Santiago Trujillo Report

0

As a first step: you want to have "Show advanced search" as a result exactly if both $("#advanced-search-painel").hasClass("hidden") and adv_text.text() == "Show advanced search" are true or both are false, so you could have:

adv_text.text(
    $("#advanced-search-painel").hasClass("hidden") == (adv_text.text() == "Show advanced search")
    ? "Hide advanced search"
    : "Show advanced search"
);

But as @CertainPerformance points out, with the constraint of adv_text.text() having only those two possible values, the if and else branch are achieving exactly the same, so there is no need for the if actually.

about 4 years ago · Santiago Trujillo 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!