Yes usually yes! That is a good practice to maintain some clarity.
I often end up calling some functions or passing some variables instead of having simple expressions/strings.
It is valuable to say that this is for one-liners purpose.
That is missing the point.
The value of the conditional operator is that it is an expression, so it can be used anywhere where a value is needed (because expressions always have to evaluate to a value - even if that value is undefined).
constage=23;letstatus='You are not adult!';if(age>=18)status='You are adult!';
With if...else the else is entirely optional. With the conditional operator an alternate expression/value has to be supplied.
Here status can't be const bound because the if may need to change it.
const still can't be used here:
constage=23;letstatus;if(age>=18)status='You are adult!';elsestatus='You are not adult!';
Without the conditional operator you have to resort to using functions in order to const bind status:
constage=23;constisAdult=()=>age>=18;conststatus=myIf(isAdult,makeAdultStatus,makeYouthStatus);functionmyIf(conditionFn,trueFn,falseFn){if(conditionFn())returntrueFn();returnfalseFn();}functionmakeAdultStatus(){// ... some expensive status generationreturn'You are an adult!';}functionmakeYouthStatus(){// ... some expensive status generationreturn`You aren't an adult!`;}console.log(status);
const age = 23;
const status = age >= 18 ? 'You are adult!' : 'You are not adult!';
It is valuable to say that this is for one-liners purpose.
Yes usually yes! That is a good practice to maintain some clarity.
I often end up calling some functions or passing some variables instead of having simple expressions/strings.
I added an example with some functions here: medium.com/@lorenzozar/javascript-...
That is missing the point.
The value of the conditional operator is that it is an expression, so it can be used anywhere where a value is needed (because expressions always have to evaluate to a value - even if that value is
undefined).if...else is a statement:
if...elsetheelseis entirely optional. With the conditional operator an alternate expression/value has to be supplied.statuscan't beconstbound because theifmay need to change it.conststill can't be used here:Without the conditional operator you have to resort to using functions in order to
constbindstatus:Expressions versus statements in JavaScript
I find that people don't tend to use the conditional operator until they clearly understand the difference between statements and expressions.
ifstatement changes the value that is bound tostatusstatusvalue based on the existingagevalue.That's a different way of thinking - similar to using .map() or .filter() to create a new array from an existing array.
Excellent addition!