Use closures for basic encapsulation when writing jQuery

If you are writing a lot of jQuery you’ll likely have files with loads of JavaScript functions and variables that may be completely independent and shouldn’t interfere with each other.

If you have a lot of this going on (or even if you don’t) you might consider wrapping up related variables & functions using closures that run immediately. These are also known as Immediately Invoked Function Expressions (IIFE) and are a fantastic approach to encapsulating your JavaScript.

A basic jQuery closure

(function ($, window, document, undefined)
// Write your jQuery here. Any JavaScript you write in here
// is scoped so you don't have to worry about symbol names
// clashing with each other.
// You can define functions in here that are only available
// in this scope.
function my_scoped_function(){ /* … */ }
})(jQuery, window, document);

In the example above, our IIFE is invoked immediately and encapsulates references to the jQuery, window, and document objects by passing them into the function.

A note on ‘undefined’

You’ll also notice that the function accepts the undefined argument with isn’t passed in when invoked.

This is just an added bonus as it simplifies undefined checks which can be a little finicky in JavaScript. By including the argument as per the snippet, you can simply check if a variable is defined using myvar !== undefined.

Need a website? Let's talk.

From website design & SEO through to custom WordPress plugin development. I transform ideas into dynamic, engaging, and high-performing solutions.
Subscribe to get the latest insights & updates in the world of web and how it impacts your business and website.
© 2024 Phil Kurth  |  All rights reserved.