Which is the better way for conditional variable assignment?
1st method
if (true) {
var myVariable = 'True';
} else {
var myVariable = 'False';
}
2nd Method
var myVariable = 'False';
if (true) {
myVariable = 'True';
}
I actually prefer 2nd one without any specific technical reason. What do you guys think?
The first solution uses only one assignment instead of 1,5 by average in the second code snippet. On the other hand the first code snippet is less readable as people not familiar with JavaScript might not realize that the scope of a variable is not block oriented by function oriented - on other languages with C-like syntax
myVariable
would not be accessible outsideif
andelse
blocks.In other words both solutions have disadvantages. What about ternary operator:
or if you don't care about the camel-case (although I understand this is just an example, not a real code);
try this
Another cool thing is that you can do multiple assignment based on a conditional:
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
orternary
statement.This works even for booleans:
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).
You could do a ternary, which is a lot shorter (and no darn curly braces):
I would prefer 2nd option too, no technical reason but for the sake of easy to read code, readability is very important in code.
If you see the second option, from processing point of view only one check will ever be executed, saved some very minute processing time, so there is only one check in second case.