I have been picking up JavaScript recently, and was wondering what the proper syntax would be for setting multiple variables for each outcome in a shorthand ternary.
Here is an example of what I currently have, a shorthand ternary that changes 1 variable if a condition is met, and changes 1 other variable if it is not.
var numberA = 5;
let rltvToTen = '';
let otherVar = '';
numberA >= 10 ? rltvToTen = 'EqualOrGreater' : rltvToTen = 'Less';
console.log(`Relative to ten: ${rltvToTen}`);
What I’m wondering is how I could make this so that if numberA >= 10, it would still set rltvToTen to the string ‘EqualOrGreater’ but would, in that same step, set otherVar to the string ‘Lorem Ipsum.’
For example, for condition?ifTrue:ifFalse, I want to set multiple actions to occur for ifTrue
(Note: I’m aware that other tactics could be applied, but I’m genuinely curious as to whether there is a proper syntax that allows multiple actions set to occur given a condition back-to-back in the shorthand form.)
(Another note: I’m towards the end of the day and running on my last braincell, so I don’t doubt I may have phrased this in an unnecessarily confusing way, and I’m sorry for that.)
I tried just putting the actions back to back.
I tried , and ; to separate multiple actions.
I tried using a space to separate multiple actions.
I tried reading the relevant documentation.
The answer to this is likely right in front of me, but I probably just can’t see it cuz I’m a skiddie newgen lmao.
3
Answers
edit: my bad, I'm blind. may have mentioned I'm running on my last braincell. my previous solution did, in fact NOT work. I was reading the loremipsum in output and failed to see the "undefined" returning for the first one. sorry @JaromandaX
Added this only because there’s a really bad answer – which, despite protestation, does not work in ANY javascript environment, if you must do this, do it like this
using grouping
()
and comma,
operatorsThough a more concise method is:
But as mentioned in the comments, there’s nothing wrong with
if
for easy to read and understand codeYou could always return and destructure an array of values to one-line the assignment