Search code examples
javascriptfunctiondomconditional-statementsconditional-operator

Convert if/else to conditional (ternary) operator


I´m new in JavaScript. I´d like to convert the conditional If to a ternary operator, but I don´t know how. I leave all the code below in case someone can help me. Thanks in advance.

<body>
  <img src="images/animal.jpg" width="200" height="200">
  <button onclick="change()" type="button">Change</button>

  <script>
    let estadoCambio = true;
    function change(){
     if (!estadoCambio){
      document.images[0].src="images/animal.jpg";
      estadoCambio = true;
     } else {
      document.images[0].src="images/flor.jpg";
      estadoCambio = false;
     }
    }
  </script>
</body>

I tried using expressions like:

  • condition ? (()=>{expresion1; expresion2})() : (()=>{expresion3; expresion4})()
  • condition ? [] : []

But no one works.

I am looking to change it by order of my programming teacher.


Solution

  • You can use destructuring to assign two variables in the conditional expression.

    [document.images[0].src, estadoCambio] = estadoCambio ? 
        ["images/flor.jpg", false] : 
        ["images/animal.jpg", true];