Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 494517
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T05:30:14+00:00 2026-05-13T05:30:14+00:00

We all know that global variables are anything but best practice. But there are

  • 0

We all know that global variables 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?

For example, given the following scenario, how would you not use a global variable?

JavaScript 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();
}

Relevant markup:

<iframe src="test.htm" name="postHere" id="postHere"
  onload="uploadCount++; if(uploadCount > 1) startUpload();"></iframe>

<!-- MUST use inline JavaScript here for onload event
     to fire after each form submission. -->

This code comes from a web form with multiple <input type="file">. It uploads the files one at a time to prevent huge requests. It does this by POSTing to the iframe, waiting for the response which fires the iframe onload, and then triggers the next submission.

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T05:30:14+00:00Added an answer on May 13, 2026 at 5:30 am

    The easiest way is to wrap your code in a closure and manually expose only those variables you need globally to the global scope:

    (function() {
        // Your code here
    
        // Expose to global
        window['varName'] = varName;
    })();
    

    To address Crescent Fresh’s comment: in order to remove global variables from the scenario entirely, the developer would need to change a number of things assumed in the question. It would look a lot more like this:

    Javascript:

    (function() {
        var addEvent = function(element, type, method) {
            if('addEventListener' in element) {
                element.addEventListener(type, method, false);
            } else if('attachEvent' in element) {
                element.attachEvent('on' + type, method);
    
            // If addEventListener and attachEvent are both unavailable,
            // use inline events. This should never happen.
            } else if('on' + type in element) {
                // If a previous inline event exists, preserve it. This isn't
                // tested, it may eat your baby
                var oldMethod = element['on' + type],
                    newMethod = function(e) {
                        oldMethod(e);
                        newMethod(e);
                    };
            } else {
                element['on' + type] = method;
            }
        },
            uploadCount = 0,
            startUpload = function() {
                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();
            };
    
        addEvent(window, 'load', function() {
            var frm = document.forms[0];
    
            frm.target = "postMe";
            addEvent(frm, 'submit', function() {
                startUpload();
                return false;
            });
        });
    
        var iframe = document.getElementById('postHere');
        addEvent(iframe, 'load', function() {
            uploadCount++;
            if(uploadCount > 1) {
                startUpload();
            }
        });
    
    })();
    

    HTML:

    <iframe src="test.htm" name="postHere" id="postHere"></iframe>
    

    You don’t need an inline event handler on the <iframe>, it will still fire on each load with this code.

    Regarding the load event

    Here is a test case demonstrating that you don’t need an inline onload event. This depends on referencing a file (/emptypage.php) on the same server, otherwise you should be able to just paste this into a page and run it.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>untitled</title>
    </head>
    <body>
        <script type="text/javascript" charset="utf-8">
            (function() {
                var addEvent = function(element, type, method) {
                    if('addEventListener' in element) {
                        element.addEventListener(type, method, false);
                    } else if('attachEvent' in element) {
                        element.attachEvent('on' + type, method);
    
                        // If addEventListener and attachEvent are both unavailable,
                        // use inline events. This should never happen.
                    } else if('on' + type in element) {
                        // If a previous inline event exists, preserve it. This isn't
                        // tested, it may eat your baby
                        var oldMethod = element['on' + type],
                        newMethod = function(e) {
                            oldMethod(e);
                            newMethod(e);
                        };
                    } else {
                        element['on' + type] = method;
                    }
                };
    
                // Work around IE 6/7 bug where form submission targets
                // a new window instead of the iframe. SO suggestion here:
                // http://stackoverflow.com/q/875650
                var iframe;
                try {
                    iframe = document.createElement('<iframe name="postHere">');
                } catch (e) {
                    iframe = document.createElement('iframe');
                    iframe.name = 'postHere';
                }
    
                iframe.name = 'postHere';
                iframe.id = 'postHere';
                iframe.src = '/emptypage.php';
                addEvent(iframe, 'load', function() {
                    alert('iframe load');
                });
    
                document.body.appendChild(iframe);
    
                var form = document.createElement('form');
                form.target = 'postHere';
                form.action = '/emptypage.php';
                var submit = document.createElement('input');
                submit.type = 'submit';
                submit.value = 'Submit';
    
                form.appendChild(submit);
    
                document.body.appendChild(form);
            })();
        </script>
    </body>
    </html>
    

    The alert fires every time I click the submit button in Safari, Firefox, IE 6, 7 and 8.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Yes I know global variables is a bad practice, but ease up on that
I know how to print all global variables using the following code for k,v
I know that global variables are bad. But if I am using node's module
First of all, I know global variables are evil :) However, there is legit
We all know that commenting our code is an important part of coding style
is there an easy way, to store all needed global variables in sessions at
We all know that RAW pointers need to be wrapped in some form of
We all know that having a good note taking tool is important as a
We all know that deadlines and/or critical bugfixes and make us forget a bit
We all know that you can overload a function according to the parameters: int

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.