Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This one has been annoying me, so I have has a play and done some tests and here are my findings.</p> <p>I will show two different pieces of script, that produce two different results, thus explaining why somebody may use one over the other. The reasons for using either however is down to the coder and will be based on the effect they want to happen.</p> <p>Note, for example purposes I will use actually values rather than empty objects.</p> <p>Normally, you might expect to see the following example in use:</p> <pre><code>var cc = cc || 1; </code></pre> <p>This creates a new variable called <code>cc</code> and gives either the value of an existing (within the same scope) variable, or a default value of <code>1</code>. This method will NOT change the original variable, although in practice it will seemingly have the effect that it has changed as you can not subsequently reference the original due to the fact it has the same name.</p> <p>This can be tested by using different variable names for example:</p> <pre><code>var aa; alert(aa); var cc = aa || 1; alert(aa); alert(cc); </code></pre> <p>(<a href="http://jsfiddle.net/musefan/HzKhJ/" rel="nofollow">Example</a>) Here you can see that <code>aa</code> never changes.</p> <p>Next we look at the code in question:</p> <pre><code>var cc = cc = cc || 1; </code></pre> <p>This will actually change the original variable AND create a new local one. Again, it is not easy to see the effects while the variables have the same name. However, if we do the same name change as above, we can see the real effect:</p> <pre><code>var aa; alert(aa); var cc = aa = aa || 1; alert(aa); alert(cc); </code></pre> <p>(<a href="http://jsfiddle.net/musefan/HzKhJ/1" rel="nofollow">Example</a>) This time we can see that <code>aa</code> does get changed.</p> <p>In conclusion, you may never actually see any effect from using one over the other (with the same variable names), but I am curious as to what effects would happen if it is possible to reference the original somewhere, prior to assignment, and therefore the choice of which to use would actually have an effect. I will see if I can find something to show this in action.</p>
 

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