Which is the better way for conditional variable assignment?
1st method
if (true) {
var myVariable = \'True\';
} else {
var myVariable = \'False\
Just for completion, there is another way in addition to all the others mentioned here, which is to use a lookup table.
Say you have many possible values, you could declaratively configure a Map instead of using an if
, switch
or ternary
statement.
Object map = {
key1: 'value1',
key2: 'value2,
keyX: 'valueX'
};
var myVariable = map[myInput];
This works even for booleans:
Object map = { true: 'value1', false: 'value2 };
var myVariable = map[myBoolean];
For booleans you would probably do it the 'normal' way though with logic operators specifically designed for that. Though sometimes it can be useful, such as:
Note there is some overlap between the advantages using a lookup map and advantages of using a function variable (closure).