6
\$\begingroup\$

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
}
\$\endgroup\$
1

2 Answers 2

14
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

Global versus local scope:

It depends on what you are working with. If you are in a framework or the javascript you are using could possibly collide with another javascript then you should localize it. Other than that, if it is a single page site, then there is no need to worry. I try to put most of my javascript in closures, but only because I work inside a framework where the possibility of collisions can be higher.

As for the two ways laid out, it is really preference in how you want to call it. They are both still global in that a call to doCancel or doCancel() can be accessed anywhere that shares scope with the script.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.