Home > Net >  Convert if/else to conditional (ternary) operator
Convert if/else to conditional (ternary) operator

Time:10-27

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.

CodePudding user response:

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];

CodePudding user response:

Multiple expressions can be wrapped in parenthesis with a comma separating them. For example:

let a, b;
(true)
  ? (a = "animal.jpg", b = true)
  : (a = "flor.jpg", b = false)
;
console.log(a,b);

(false)
  ? (a = "animal.jpg", b = true)
  : (a = "flor.jpg", b = false)
;
console.log(a,b);

  • Related