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);
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...else
theelse
is entirely optional. With the conditional operator an alternate expression/value has to be supplied.status
can't beconst
bound because theif
may need to change it.const
still can't be used here:Without the conditional operator you have to resort to using functions in order to
const
bindstatus
: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.
if
statement changes the value that is bound tostatus
status
value based on the existingage
value.That's a different way of thinking - similar to using .map() or .filter() to create a new array from an existing array.
Excellent addition!