Sebastian Valentine Sebastian Valentine - 2 years ago 68
HTML Question

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

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

<!DOCTYPE html>

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

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

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

function stopColor() {


Answer Source

It's the ternary operator.

condition ? expr1 : expr2

Which is the same as:

if (condition) expr1;
else expr2;

So in your case: = == "yellow" ? "pink" : "yellow"

Is equivalent to:

if ( == "yellow") = "pink";
else = "yellow";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download