Ternary Operator Tutorial
EasyProgramming.net tutorial #22 - ternary operator
by Nazmus Nasir
HTML
<!-- Easy JavaScript # 22 - ternary operator -->
<p>
Welcome to the 22nd Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. In this tutorial, we complete our look at conditions by going over the ternary operator.
</p>
<p>
The ternary operator is a great way to write conditional statements in shorthand, more specifically, the if statement. In fact, you can write fairly complex conditions in just one line of code.
</p>
<p>
Creating conditional statements will allow you to create and manage custom workflows for you and your users. There is always more than one way to use a web application,
</p>
<h2>
Syntax using the ternary operator:</h2>
<p>
<code><pre>
(if condition true) ? do this : else do this;
(if condition1 true) ? do this : (else condition2 true) ? do this : else do this;
</pre>
</code>
</p>
<p>
<h2>
Let's practice:</h2>
The color is <span id="color">___</span>
<br /><br />
JavaScript
var price = 3;
(price == 1) ? console.log("one") : (price == 2) ? console.log("two") : console.log("it's neither");
var color = 'red';
var output = document.getElementById("color");
(color == 'red') ? (output.innerText = "red", output.style.color = 'red') : (output.innerText = "something else", output.style.color='purple');
/*if(color == 'red'){
output.innerText = "red!";
output.style.color = 'red';
} else if(color == 'blue'){
output.innerText = "blue!";
output.style.color = 'blue';
} else if(color == 'green'){
output.innerText = "green!";
output.style.color = 'green';
} else {
output.innerText = "something else";
output.style.color = 'purple';
}*/