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!