Ternary operator in JavaScript

Are you learning JavaScript and came across the term ternary operator? In this article, we will learn what is ternary operator in JavaScript or TypeScript and also how it is implemented.

What is Ternary Operator?

Well, Ternary Operators are insanely helpful when you’re trying to write concise and quick lines of code. Basically, Ternary Operator works exactly like “if-else” conditioning, but instead of using those traditional “if” and “else” clauses with their coding block, Ternary Operator can be a 1 liner. It checks if the condition is true or false and acts accordingly. Simple right!  

Let’s look at an example of how exactly ternary operator in JavaScript works: 

 

Instead, you do this whole thing in just 1 line with ternary operator, like so: 

				
					var a = 25; 
var b = 22; 

If( a > b ){ 
    console.log( "a is greater than b" ); 
} 
else { 
    console.log( "b is greater than a" ); 
} 
				
			
				
					a>b ? console.log( "a is greater than b" ) : console.log( "b is greater than a" )
				
			
How Ternary Operator Works
How Ternary Operator Works

The condition before the “?” symbol, if its true, then the code right after the “?” will get executed and it won’t ahead from there. But if that condition is false, it will directly run the code that’s after the “:” symbol. 

And you’re done!