Javascript conditional | ternary operator with example

In this tutorial, we will learn about the javascript ternary / conditional operator also known as the shorthand of if-else condition in single line or it is a shortcut for the if-else condition.

Ternary operator example:

The syntax for the ternary operator:

condition ? ExrepressionOne : ExpressionTwo

Condition: an expression whose value we will use as a condition. If the condition is true then experssionOne will be evaluated otherwise expressionTwo will be evaluated. 

Example of ternary operator

userType == 'admin' ? console.log('admin') : console.log('not admin');

if the userType == 'admin' it will print admin and if the conditon doesnot meet then it will print not admin. The above example is equivalent to below example.

if (userType == 'admin') {
	console.log('admin');
} else {
	console.log('not admin');
}

Ternary operator conditional chains

In this section, we will see the example of conditional chains if elseif else in single line.

Syntax:

conditionOne ? expressionOne
     : conditionOne ? expressionTwo
     : conditionThree ? expressionThree
     : expressionThree;

In the above syntax if the conditionOne is false then it will go to conditionTwo and check. if conditionTwo is false it will go to conditionThree and so on.

Example of Ternary operator conditional chains

Below is the example of ternary operator conditional chains

userType == 'admin' ? console.log('admin')
	: userType == 'author' ? console.log('author')
	: userType == 'writer' ? console.log('writer')
	: console.log('not a user');

Take a look at the below example it is equivalent to the above example.

if (userType == 'admin') {
	console.log('admin');
} else if (userType == 'author') {
	console.log('author');
} else if (userType == 'writer') {
	console.log('writer');
} else {
	console.log('not a user');
}

The above example is if the userType == 'admin' it will print admin or if the userType == 'author' it will print the author and so on and if all the condition is false it will print the not a user.