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

301
Views
How can I rewrite this code using a ternary operator?

The following is a code I have written to change a grid color to indigo upon clicking it, then removing the color upon the second click. However, I do not know how to rewrite the if-else statement using a ternary operator.

const grid1=document.querySelector(".cell01")
grid1.addEventListener("click", (e)=>{
    console.log(e);
    if (grid1.style.backgroundColor) {
      grid1.style.backgroundColor = "";
      } else {
        grid1.style.backgroundColor = "indigo";
      }
})

Thank you for your help in advance (:

Update Thanks for the answers! But now I have one more inquiry -- I wanted to try different ways of rewriting the same code, and came up with this:
grid1.style.backgroundColor=(grid1.style.backgroundColor!=true) ? "indigo" : "";

It did exactly what I wanted with the expression (grid1.style.backgroundColor==false), but not in the case of the former. Is there a reason why?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Straightforward translation into a ternary:

grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo"; 
about 4 years ago · Juan Pablo Isaza Report

0

grid1.style.backgroundColor = grid1.style.backgroundColor ? '' : 'indigo'
about 4 years ago · Juan Pablo Isaza Report

0

You can try this:

grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo";

Checkout below reference to learn more about ternary operator https://www.freecodecamp.org/news/ternary-operator-javascript-if-statement-tutorial/

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!