0

What is this line of code in JavaScript x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";" in the program written below?

   <!DOCTYPE html>
   <html>
   <body>

   <p>In this example, the setInterval() method executes the setColor()       function once every 300 milliseconds, which will toggle between two background   colors.</p>

   <button onclick="stopColor()">Stop Toggling</button>

   <script>
   var myVar = setInterval(function(){ setColor() }, 300);

   function setColor() {
   var x = document.body;
   x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" :    "yellow";
   }

   function stopColor() {
   clearInterval(myVar);
   }
   </script>

  </body>
  </html>
timolawl
  • 5,434
  • 13
  • 29
Sumit
  • 486
  • 4
  • 16

1 Answers1

4

It's the ternary operator.

condition ? expr1 : expr2

Which is the same as:

if (condition) expr1;
else expr2;

So in your case:

x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow"

Is equivalent to:

if (x.style.backgroundColor == "yellow")
    x.style.backgroundColor = "pink";
else x.style.backgroundColor = "yellow";
timolawl
  • 5,434
  • 13
  • 29