Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to avoid global variables in JavaScript?
    primarykey
    data
    text
    <p>We all know that <a href="http://en.wikipedia.org/wiki/Global_variable" rel="noreferrer">global variables</a> are anything but best practice. But there are several instances when it is difficult to code without them. What techniques do you use to avoid the use of global variables?</p> <p>For example, given the following scenario, how would you not use a global variable?</p> <p><strong>JavaScript code:</strong></p> <pre><code>var uploadCount = 0; window.onload = function() { var frm = document.forms[0]; frm.target = "postMe"; frm.onsubmit = function() { startUpload(); return false; } } function startUpload() { var fil = document.getElementById("FileUpload" + uploadCount); if (!fil || fil.value.length == 0) { alert("Finished!"); document.forms[0].reset(); return; } disableAllFileInputs(); fil.disabled = false; alert("Uploading file " + uploadCount); document.forms[0].submit(); } </code></pre> <p><strong>Relevant markup:</strong></p> <pre><code>&lt;iframe src="test.htm" name="postHere" id="postHere" onload="uploadCount++; if(uploadCount &gt; 1) startUpload();"&gt;&lt;/iframe&gt; &lt;!-- MUST use inline JavaScript here for onload event to fire after each form submission. --&gt; </code></pre> <p>This code comes from a web form with multiple <code>&lt;input type="file"&gt;</code>. It uploads the files one at a time to prevent huge requests. It does this by <a href="http://en.wikipedia.org/wiki/POST_%28HTTP%29" rel="noreferrer">POST</a>ing to the iframe, waiting for the response which fires the iframe onload, and then triggers the next submission.</p> <p>You don't have to answer this example specifically, I am just providing it for reference to a situation in which I am unable to think of a way to avoid global variables.</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