NeoBrutalist University

Closure Crisis: A Guide to Not Losing Your Mind

Are you tired of your codebase being a tangled mess of callbacks and closures? Do you find yourself wondering if anyone has ever managed to tame the beast that is JavaScript?

Look no further! This comprehensive guide will walk you through the basics of closures, from the simple to the absurd.

First, let's start with the basics: what is a closure, anyway?

				// A basic closure in action
				function outer() {
					let x = 10;
					return function inner() {
						return x;
					}
				}
				let closure = outer();
				console.log(closure()); // 10
			

As you can see, a closure is simply a function that has access to its own scope. But what happens when things get more complicated?

Let's say we want to create a closure that has access to an object with some state:

				// A closure with some state
				let person = {
					firstName: 'John',
					lastName: 'Doe'
				};
				function outer() {
					return function inner() {
						return person.firstName + ' ' + person.lastName;
					}
				}
				let closure = outer();
				closure(); // John Doe
			

And what about when we want to create a closure that has access to a function with some state?

				// A closure with a function that has state
				let counter = 0;
				function outer() {
					return function inner() {
						counter++;
						return counter;
					}
				}
				let closure = outer();
				closure(); // 1
				closure(); // 2
				closure(); // 3
			

And what about when we want to create a closure that has access to both an object with state and a function with state?

				// A closure with both state and function state
				let person = {
					firstName: 'John',
					lastName: 'Doe'
				};
				let counter = 0;
				function outer() {
					return function inner() {
						counter++;
						return person.firstName + ' ' + person.lastName + ': ' + counter;
					}
				}
				let closure = outer();
				closure(); // John Doe: 1
				closure(); // John Doe: 2
				closure(); // John Doe: 3
			

And finally, what about when we want to create a closure that has access to an array with state?

				// A closure with an array with state
				let arr = [1, 2, 3];
				function outer() {
					return function inner() {
						return arr.shift();
					}
				}
				let closure = outer();
				closure(); // 1
				closure(); // 2
				closure(); // 3
			

And that's it! With these examples, you should now have a good understanding of closures and their uses in JavaScript. But don't just take our word for it – try it out for yourself and see the power of closures in action!

Next up in our JavaScript Links Jamboree series: Prototype Pitstop