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" )
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!
Recent Comments
Categories
- Angular
- AWS
- Backend Development
- Big Data
- Cloud
- Database
- Deployment
- DevOps
- Docker
- Frontend Development
- GitHub
- Google Cloud Platform
- Installations
- Java
- JavaScript
- Linux
- MySQL
- Networking
- NodeJS
- Operating System
- Python
- Python Flask
- Report
- Security
- Server
- SpringBoot
- Subdomain
- TypeScript
- Uncategorized
- VSCode
- Webhosting
- WordPress
Search
Recent Post
Understanding Mutex, Semaphores, and the Producer-Consumer Problem
- 13 October, 2024
- 10 min read
Process scheduling algorithm – FIFO SJF RR
- 14 September, 2024
- 8 min read
How to Implement Multithreading in C Language
- 8 September, 2024
- 9 min read