Which is the better way for conditional variable assignment?
1st method
if (true) {
var myVariable = \'True\';
} else {
var myVariable = \'False\
An alternative way of doing this is by leveraging the ability of logical operators to return a value.
let isAnimal = false;
let isPlant = true;
let thing = isAnimal && 'animal' || isPlant && 'plant' || 'something else';
console.log(thing);
In the code above when one of the flags is true isAnimal
or isPlant
, the string next to it is returned. This is because both &&
and ||
result in the value of one of their operands:
Answer inspired by this article: https://mariusschulz.com/blog/the-and-and-or-operators-in-javascript
PS: Should be used for learning purposes only. Don't make life harder for you and your coworkers by using this method in your production code.