IIFE, or an immediately-invoked function expression, is something that’s been a relatively common way of writing code in JavaScript.

It’s something that I think anyone doing any type of client-side development with WordPress should be using, but first I think it’s important to grasp the concept. Wikipedia provides a definition of IIFE:

An immediately-invoked function expression (or IIFE, pronounced “iffy) is a JavaScript programming language idiom which produces a lexical scope using JavaScript’s function scoping.

If you’re new to JavaScript, that just sounds kind of intense, right? So perhaps a better definition might be:

An “iffy” defines how variable names are related to the functions in which they are contained. Inner functions maintain the scope of their parent functions.

And finally, these functions are invoked anonymously because the function that fires literally has no name. It’s fired when the browser loads, parses, and runs the script.

So how does this all relate to WordPress?

IIFE in WordPress

Since WordPress ships with jQuery, I very infrequently (read: almost never) use anything outside of the jQuery library. It’s easier for a variety of reasons most of which are irrelevant to this post.

IIFE Scoping

This is not the type of scoping that I really had in mind.

First, here’s the usual boilerplate code I use to setup a JavaScript file:

Secondly, this is one way to begin defining functions within in this iffy (and having the variables and thus functions be lexically scoped:

That said, the code can get unwiedly if you load up a single file full of functions like this. Instead, there are other patterns – like the module pattern – or even other ways to go about handling this in terms of setting up separate files.

Why Bother?

But that’s outside the scope – and it’d be so easy to make a pun here – of this post. The bottom line of this post is that if you’re a WordPress developer, please look into using IIFE in your JavaScript.

It makes it easier to maintain, less likely to conflict with other source code and follows a better practice than many other alternatives that you may find around the web.


    Leave a Reply