Why you should be using the JavaScript ternary operator.

Introduction

As developers, we have undoubtedly run into if-else statements throughout our career. Kind of like the plague, if-else statements are something that just can’t be avoided in any projects of note. But what if I told you there is a way in JavaScript to condense your if-else statements into one line? Let me introduce you to the ternary operator!

What is a Ternary Operator?

A ternary operator, otherwise known as a conditional operator, is a JavaScript operator that is commonly used as a shortcut for if-else statements. A ternary operator is made up of three main operands: a condition that must evaluate to true or false, an expression if the condition is true, and another expression if the condition is false. This syntax allows us to condense an otherwise multi-line if-else statement into a single line, which helps you to write code faster.

How do you Write a Ternary Operator?

Using a ternary operator in JavaScript is relatively simple, and, in my opinion, not hard to remember at all. When writing a ternary operator you must first write the condition followed by a question mark. After this, you write the expression if the condition is true, followed by a colon ( : ), then the expression if the condition is false. The syntax is something like this:

condtion ? expressionIfTrue : expressionIfFalse 

#programming #javascript #coding #computer-science

How to Create If Statement One-Liners Using JavaScript
1.50 GEEK