Being a "newb" to Javascript syntax can be a bit overwhelming at times. For starters, you can solve any single problem 10 different ways. Which means, you can write the syntax a few different ways to get the same result. Thats why on my latest discovery (The conditional ternary operator) it prompt: (me to write this article).
Lets dive deeper
What in the world is a ternary?
The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.
Ternary Syntax
condition ? expr1 : expr2
if the condition
is true
the operator returns the value of expr1
; otherwise it returns the value of expr2
Lets go though some examples IF/ELSE
let age = 16;
if(age > 18){
console.log('You meet the requirement');
}else {
console.log('Not yet!');
}
same example; revised
let age = 16;
let ageRequirement = age > 18 ? 'You meet the requirement' : 'Not yet!';
console.log(ageRequirement); // 'Not yet!'
Ternary's can also have multiple conditions and expressions.
Conclusion
This is obviously a very basic explanation as to how Ternary's work. My objective is the bring awareness to those who are new to writing Javascript like me. Here is a great resource on the MDN that explains in great detail how to effectively use ternary's in your Javascript code.
Top comments (10)
It's worth noting that ternaries work in setting values not executing statements.
can't be reduced to
Though I do think it reads easy (even nested) so long as what you're assigning is simple.
Having longer strings is where it gets to be cleaner to just write out the if-else.
There's nothing that would prevent a ternary from executing statements. That statement is perfectly valid JavaScript.
Really? I never saw that as a valid option in IntelliJ within the Jasmine/ES5 realm :o Nice!
Thanks for a really concise writeup.
I agree with @tux0r on this one. Ternary statements are awesome for showing off fancy JS skills, but in practicality, they're very hard on the eyes.
To add to the madness, you can chain ternary statements together ad nauseum. At that point, it's less about fanciness and more about "just because you can, doesn't mean you should."
To tux0r's point, if you're reading the code in your head as if condition, then expression, why not write it out as such?
Since ternaries push you to use expressions, it makes your code less about control flow (if this, do that, else do something else) and more about "given this and that, send this value back".
It's very easy to write a lot of code in the if/else that should have been written as a set of functions acting one after the other to transform the data.
Of course if you've got small functions and aren't doing much within your if/else, it'll help long term maintainability.
console.log(ageRequirement); instead of console.log('ageRequirement');
Thank you will update that shortly.
U're welcome mafriend! :)