Angry Birds of JavaScript- Red Bird: IIFE

Introduction

A diabolical herd of pigs stole all of the front-end architecture from an innocent flock of birds and now they want it back! A team of special agent hero birds will attack those despicable pigs until they recover what is rightfully theirs, front-end JavaScript architecture!

In this post we will take a look at the Red Bird who attacks with the force of their trusty IIFE, the basic block of all privacy.

What Was Stolen by the Pigs?

For ages the birds used to litter the global namespace (the window object) with their custom objects and functions. Over time the birds slowly learned techniques to protect their objects from the global namespace, however, since the recent pig invasion all of their anti-global secrets have been stolen! Thankfully the birds are fortunate that a one foul exists with the knowledge of this secret and plans to attack the pigs to unleash what is rightfully theirs.

How Objects Become Global?

There are several ways that an object can become global. Part of the battle is just knowing the various ways.

  1. Declaring an Object in the Window Scope

In the following example there two variables declared, type and attack. These variables were declared in the top level scope and therefore are accessible off of the window object.

  1. Not Declaring an Object in Any Scope

One of the most dangerous and easiest things to do in JavaScript is to accidentally declare a global variable when you didn’t mean to. If you forget to declare a variable then JavaScript declares it for you as a global! This is usually not what you meant to do and could expose parts of your application that you didn’t intend.

  1. Specifically Adding an Object to the Window

You also have the opportunity to expose variables to the global namespace intentionally. You can easily do this by accessing the window object and adding a property or method manually. It isn’t a good idea to use this technique deep inside your code, but it is worth nothing that you can.

Why Are Global Objects a Problem?

Various Ways to Protect Yourself

Although the above code snippets were very small and simple, they all exposed way too many variables to the global namespace. So, how do we protect ourselves?

Attack!

The following is a simple Angry Birds clone using boxbox, a framework for the box2dweb JavaScript physics library, written by Bocoup’s Greg Smith.

Press the space bar to launch the Red Bird and you can also use the arrow keys.

Conclusion

These techniques are vital for a front-end application so that it can protect itself from other code and it also gives the opportunity to structure your code in a way that is encapsulated from its surroundings.

There are many other frotn-end architecture techniques that have been stolen by the pigs. Tune in next time as the next Angry Bird takes its revenge! Dun, dun, daaaaaaa!