HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Should I put a JavaScript function in a local or global scope?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
localglobaljavascriptfunctionputscopeshould

Problem

I have many pages with functions that appear only once, which I am sure is really typical. I read that it's the best idea to use the local scope for functions when possible because the local scope is searched first, thereby making the function found sooner.

If I have no intention of reusing a function, is this the best way to create and use this function?

var doCancel = function doCancel() {
    // DO SOME CANCELLING TYPE STUFF
}


Or is this a better way?

function doCancel() {
    // DO SOME CANCELLING TYPE STUFF
}

Solution

I always wrap my code in an IIFE:

(function () {
    'use strict';

    //code here
}());


I also pass in all global variables I am going to use in this code block:

(function (window, document, $) {
    'use strict';

    //code here
}(window, document, jQuery)); //...


If I am going to expose any global variables I explicitly add them to the global scope at the end of this function (but I avoid this if it is at all possible):

(function (window, document, $) {
    'use strict';

    //code here

    window.XXX = somelocalreference;
}(window, document, jQuery)); //...


This way I never unexpectedly leak globals and I can know that my code is not going to give me problems with future changes that my coworkers or myself make.

See also: Responsive/adaptive website code

Code Snippets

(function () {
    'use strict';

    //code here
}());
(function (window, document, $) {
    'use strict';

    //code here
}(window, document, jQuery)); //...
(function (window, document, $) {
    'use strict';

    //code here

    window.XXX = somelocalreference;
}(window, document, jQuery)); //...

Context

StackExchange Code Review Q#12511, answer score: 14

Revisions (0)

No revisions yet.