Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Logical AND in Javascript Variable Declarations
    primarykey
    data
    text
    <p>I am interested in the practical application of declaring variables using <code>&amp;&amp;</code> like this:</p> <pre><code>var x = undefined &amp;&amp; 4; // Evaluate to the first falsey value // or else the last value. eval(x); // undefined </code></pre> <p>I understand how the value is evaluated (see <a href="https://stackoverflow.com/a/7602012/1351736">this SO answer</a>). I also understand its sister <code>||</code> (see <a href="https://stackoverflow.com/a/476445/1351736">here</a> for a great description) and why it would be useful to declare a variable with the following expression:</p> <pre><code>// Some other variable var y; var x = y || 4; // Evaluate to the first truthy value // or else the last value. </code></pre> <p>Practically: Use the first value unless that first value is falsey; if so, use the last value. We can demonstrate this characteristic of <code>||</code> in the browser console:</p> <pre><code>&gt; null || 4 4 &gt; 4 || null 4 &gt; null || undefined undefined &gt; undefined || null null &gt; true || 4 true &gt; 4 || true 4 </code></pre> <p>As for <code>&amp;&amp;</code>:</p> <pre><code>&gt; null &amp;&amp; 4 null &gt; 4 &amp;&amp; null null &gt; null &amp;&amp; undefined null &gt; undefined &amp;&amp; null undefined &gt; true &amp;&amp; 4 4 &gt; 4 &amp;&amp; true true </code></pre> <p>Should we take this to mean: Use the first value unless that first value is truthy; if so, use the last value?</p> <p>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.</p> <p>I found an example of this coding method in <a href="https://github.com/jquery/jquery/blob/451d0c37d9297598743b1372bf623d4b7d38e951/src/core.js#L472" rel="nofollow noreferrer">line 472</a> of the jQuery core source:</p> <pre><code>scripts = !keepScripts &amp;&amp; []; </code></pre> <p>So the question is this: Can anyone describe a good context for using <code>&amp;&amp;</code> in a javascript variable declaration? Do you consider it to be bad practice?</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload