I am interested in the practical application of declaring variables using &&
like this:
var x = undefined && 4;
// Evaluate to the first falsey value
// or else the last value.
eval(x);
// undefined
I understand how the value is evaluated (see this SO answer). I also understand its sister ||
(see here for a great description) and why it would be useful to declare a variable with the following expression:
// Some other variable
var y;
var x = y || 4;
// Evaluate to the first truthy value
// or else the last value.
Practically: Use the first value unless that first value is falsey; if so, use the last value. We can demonstrate this characteristic of ||
in the browser console:
> null || 4
4
> 4 || null
4
> null || undefined
undefined
> undefined || null
null
> true || 4
true
> 4 || true
4
As for &&
:
> null && 4
null
> 4 && null
null
> null && undefined
null
> undefined && null
undefined
> true && 4
4
> 4 && true
true
Should we take this to mean: Use the first value unless that first value is truthy; if so, use the last value?
I'm interested in using coding shortcuts to minimize the use of conditional statements, and I wonder if I might be able to use this one somehow.
I found an example of this coding method in line 472 of the jQuery core source:
scripts = !keepScripts && [];
So the question is this: Can anyone describe a good context for using &&
in a javascript variable declaration? Do you consider it to be bad practice?
Thanks!
In general, you should only only use "shortcuts" like this if it makes the code more readable for the typical JavaScript programmer than the alternative.
When thinking about what is more readable, and less surprising, consider that
var foo;
if(bar) {
foo=[];
}
and
var foo = bar && [];
are not the same. For instance, if bar
is NaN
, then foo
will then be NaN
in the later case, which might be a bit of a head-scratcher later on.
Since there are tools to optimize/minimize JavaScript, you should focus on readability of your code, which is not always the same thing as brevity.
Lets say you have several such repetitive initializations in a row, all dependent on different variables (so that they couldn't be wrapped into a single conditional), but following the same logical formula. In this case, once the reader had mentally parsed the meaning of the formula, they could quickly scan all the instances and see the differences between each one. In this case, instead of relying on a convention that most JavaScript programmers are familiar with (such as var foo = some_opt || {}
), you are creating a localized convention, that the reader will have to learn just for this file. Even in this case, I'd advise some careful consideration, its probably not worth it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With