JavaScript Inception

Note: The following whimsical post assumes that you have seen the movie Inception. If you haven't yet, and you don't want to run the risk of spoilers, then I'd encourage you to see the movie before reading any further.

JavaScript - The browser is the scene of the crime

If you know me in person, then you're well aware that I love to speak in analogies, especially when it comes to teaching others about an abstract topic. Coworkers chuckle when I begin my sentences with "It's kind of like…" Lately I have been obsessed with the movie Inception. I have seen it three times in the theater already, and have been using it as a reference point to talk about JavaScript.

In fact, I'm fairly convinced that Christopher Nolan must himself be a JavaScript developer at heart. I mean, he named his main character DOM, didn't he? It's also interesting the antagonist is named Mal, which makes me think Malware.

Anyway, I thought I would share some interesting, or hopefully at least humorous, metaphors for our beloved — yet oft misunderstood — client side programming language. First off, let's start with the planning phase of a web project. It is not unlike the characters brainstorming how to execute their perfect crime.


Inception - planning

As a developer, you definitely don't want to jump in unprepared. You want to have a strategy and an understanding of the surrounding and underlying architecture. From a JavaScript standpoint, this typically means agreeing on a standard approach to coding, with many teams choosing to use the Module Pattern.

In the movie, without an agreed upon course of action, they run the risk of "dying" and falling into unconstructed dream-space or "raw subconscious." So it is with JavaScript. You want to keep things neat and under control, else your name-space can be destroyed. See what I did there? Meh. Okay. Moving on…

DOM Manipulation

Inception - DOM manipulation

Another parallel to the movie is that at any given moment, they can mess with the physics of their imagined world. But in so doing, they run the risk that their subject may become alert('suspicious') to the fact that they are not in the real world. So it is with web development. If we are to invite the user to enter our site, we must not change the page so drastically beneath their feet that they become disoriented and exit our "dream." DOM manipulation must be done with care.

Variable Scope

Inception - global variable

A big mistake that many beginner JavaScript dabblers make is forgetting to declare variables with the var keyword. Neglecting to do so puts the variable in the global scope. Let's say we attempted to create and contain a variable named Mal

(function () {
	Mal = 'Angry assassin!';

if (Mal) {
	// Alerts "Angry assassin!"

Even though we've attempted to lock her away within the scope of a function, because we didn't use the var keyword, she escapes to wreak havoc on other levels above and below. This has the potential to considerably ruin a dinner party.

This is the proper way to declare a variable. Note the three letter word var that precedes the actual variable name Mal. Sometimes, that's what makes the difference between a solid application, and one riddled with (bullet?) holes…

(function () {
	var Mal = 'Angry assassin!';

if (Mal) {
	// Does not execute.
	// Get it? "Execute," haha!

Event Bubbling

Inception - event bubbling

Another frequently overlooked concept in JavaScript is how events are handled. Let's say we have the following HTML structure, with nested "dream" levels…

<div id="real_world">
	<ul class="dream_1">
		<li class="dream_2">
			<span class="dream_3">
				<a href="#" class="the_kick">Click Me</a>

If you click the link, not only does the <a> tag itself receive the click, but so do the <span>, <li>, <ul>, and <div>… all the way up the chain to the <body>. This is referred to as event bubbling. In the early days of JavaScript, this was thought of as an oddity and even a nuisance. But in our shared enlightened state of mind now, we realize it can be used to our advantage. In fact, it is this concept of event delegation that makes possible the handy jQuery .on() method.

// This only works on elements that
// are present when the code runs…

$('#real_world a.the_kick').on('click', function () {
	// Do something.

// This works on all present and future
// elements that match the criteria…

$('#real_world').on('click', 'a.the_kick', function () {
	// Do something.

That first function above works only on elements that already exist when the function is called, typically when the page loads. After that initialization, if more elements are inserted to the page, they will not have the click event bound to them. This is because unobtrusive event listeners (though similar in syntax to CSS via jQuery) are not like CSS. While newly inserted elements have the same visual treatment applied by a stylesheet, their behavior reverts to default.

The second function above makes use of event delegation, by cleverly applying a click event listener to the #real_world element, and then asking when it is clicked: "Did this event also take place on an element matching a.the_kick? It did? Splendid! Let's kick off the contents of its event listener function."

You could think of this like the multiple simulated "kicks" that are fired off, which eventually bring the dreamers back up to the top level, where they awake in the airplane. Inversely, you can think of the event listeners as being wrappers around each of the subsequent dream layers, waiting for key things to happen.

The End

Another passing thought is that each browser's JavaScript engine is a bit like the sedative / brain accelerant that the dreamers take. Depending on which formula is applied, such as Google's V8, a considerable speed boost can be gained!

So yeah, those are my meandering ruminations on how Inception can be used to explain JavaScript to your friends, family, neighbors, and coworkers. I just thought I would share, in case these analogies might benefit anyone else.