With the first approach you have a variable that is initialized to a value the moment it is created. Adding additional lines between the declaration and if
statement means you have some meaningful information already in the variable.
let variable = someDefaultVariable();
// We know `variable` is some sort of default value, so we
// can predict a sensible result
let variable2 = variable + 3;
if (some_boolean) {
variable = someOtherValue();
}
Contrast that with the second example where adding lines of code in between the variable declaration and the first if
statement ends up working with an uninitialized value:
let variable;
// Here `variable` is undefined, so we get a NaN result at
// run time, but while your coworkers are reading this code
// they might think it will result in a number.
let variable2 = variable + 3;
if (some_boolean) {
variable = someOtherValue();
} else {
variable = someOtherValue();
}
Code evolves. Leaving variables uninitialized leaves little potholes in the roadway that is your programming logic. It's all to easy to miss things like this when changing code — especially someone else's code.
Go for:
Correctness (making sure variables are initialized to something is part of "correctness")
Readability and understandability
Since this is JavaScript, do not go for optimizing for memory usage or memory layout.
This sort of thing does not exist in the ECMA Script spec, mostly so JavaScript interpreters can have free reign to optimize as they see fit.
As mentioned in another answer and in comments, the ternary operator can make this a one-liner, which you can split into multiple lines for readability:
let variable = some_condition
? someValue()
: someOtherValue();
This becomes unreadable when the variable has 3 or more possible values upon initialization. In that case you can always put the calculation of the initial value into another function:
let variable = calculateValue(some_condition);
And then calculateValue gets to deal with the if
statement:
function calculateValue(condition2) {
if (condition1) {
return value1;
}
else if (condition2) {
return value2;
}
return defaultValue;
}
if
andelse
to do the assignment. Just use the ternary operator, which simplifies the code and assigns (once) via the declaration.