Javascript ternary operator

The conditional (ternary) operator is the only JavaScript operator that uses three operands in syntax. This operator is frequently used as a shortcut replacement for the if else statement. Normally this operator is used for small conditions like setting a default value of a variable based on conditions.


	condition ? expr1 : expr2 


condition – Any valid JavaScript condition
expr1 – Returns this expression if condition evaluates to true
expr2 – Returns this expression if condition evaluates to false

Above statement executes as follow : if condition is true, then the operator returns the value of expr1 otherwise it returns the value of expr2.

<!DOCTYPE html>

<p>Click on button to increment counter</p>

<input id="count" value="" />

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

function myFunction() {
	var count=document.getElementById('count').value;
    count = count > 0 ? ++count : 1;

    document.getElementById("count").value = count;


Download the code Run the code

If value of count is above 0, then its value is incremented by 1 otherwise it is set as 0. It is also possible to combine multiple ternary operators to make a complex conditional logic. Normal if else statement can be used in place of ternary operator. Ternary operator is more readable many times.

For example, below condition is more readable

var now = new Date();
var greetings = 'Good' + (now.getHours() > 12 ? 'Afternoon' : 'Day');

than its if else version shown below.

var now = new Date();
var greetings = 'Good';
if (now.getHours() > 12)
    greetings + = 'Afternoon';
    greetings + = 'Day';
<<< JavaScript OperatorsJavascript typeof Operator >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .