Loading, please wait...

A to Z Full Forms and Acronyms

Different ways to write Conditional Statements in Java Script

Conditional Statements in Java Script

❌ Did you know in JavaScript there are different ways to write Conditional Statements and one of the ways to write them is using Ternary Operators?

If you see code that looks like this👇🏽

function dontGetCoronaVirus() {
if(coronaVirus) { advice= "Please stay home"; } else { advice = "You're can go outside now"; }


It can get refactored to this 👇🏽

let advice = coronaVirus? "Please stay home" : "You're can go outside now";

Now, what are Ternary Operators in JavaScript? 💡

Ternary Operators are the shorthand version of "if...else" statements (conditionals). It's also the only operator in JavaScript that works with 3 operands. .
✅The syntax is: <condition> ? <expression 1> : <expression 2>

🧠 What does his code do?

  1. The <condition> is the value that will be tested and evaluated as a boolean. Depending on the result, the operator will run both expressions.
  2. If the <condition> is true it'll execute <expression 1>
  3. Else (see what I did there? ) the <expression 2> is false it will execute the second one.

🔸Things to note:

-`?` means `IF` and `:` means `else`.
- The <expression> can be value(s) of any type that can be evaluated as a boolean.

Ternary operators are a great way to write conditionals as long as it doesn't affect code readability and maintainability. With that said, use them responsibly. Use ternary operators when it makes sense but always optimize for readability.

What are your thoughts on ternary operators? 🤔

A to Z Full Forms and Acronyms

Related Article