Sebastian Valentine Sebastian Valentine - 7 months ago 11
HTML Question

What is the ? in JavaScript and how does it work?

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>

Answer

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";
Comments