Skip to content
Swizec Teller - a geek with a hatswizec.com

Closure and currying magic for cleaner javascript

Sometimes you find a piece of javascript, a perfect piece of javascript, it does exactly what you need! Perfect! You could spend hours, even days, getting something to work and someone's already done it, shared the code on the internets even!

Hooray!

But ... the code looks something like this:

// to populate later
var data = [],
oldData = [],
semiOldData = [];
var a_switch = "blah";
function do_something() {
// use subset of globals
}
function something_else() {
// use some other globals
}
// etc.
function update() {
// use all of the above
}

The code works ... if you only need to use it once. What if you need two independent widgets? Well, you could take the time to recode all of that so it becomes purely functional.

But that's going to be a problem - the code heavily relies on state. Ok maybe object oriented? Object oriented kind of sucks in javascript and you'd have to recode all of that, have to perfectly understand it etc.

Pain in the arse!

Closure magic

There's a better way - put it in a closure.

var my_widget = function (data_function) {
// to populate later
var data = [],
oldData = [],
semiOldData = [];
var an_index = 1;
function do_something() {
// use subset of globals
}
function something_else() {
// use some other globals
}
// etc.
function update(index) {
an_index = index;
data = data_function();
// use all of the above
}
return update;
};

Now you get to create the widget with a simple function call. Hooray!

And the function returns its own update function so you can run an update whenever you need. All the state and weirdness is neatly packaged inside the closure, the code itself doesn't need to know anything about the outside state.

By changing the update function a little bit you can even affect the internal state of the closure by calling the curried function.

Closures upon closures

Here's where it gets even more magical. Stacking closures to achieve true greatness.

Code is the best way to explain what I mean ...

// these functions are used to slice up data
var slice_functions = {
students: function (item) { return !!item.cs_student; },
others: function (item) { return !item.cs_student; },
everyone: function (item) { return true; }
},
slice_func = slice_functions.students,
// these functions provide cleaned up data
// all must use the same main slice_func
data_functions = {
year_vs_pay: function (year) {
var data = DATA.filter(slice_func).filter(function (item) {
return item.years_study == year;
}),
// ...
return fin_data;
},
study_vs_pay: function (study) {
var data = DATA.filter(slice_func).filter(function (item) {
return item.study_time == study;
}),
// ...
return fin_data;
},
// ...

Those are our data functions, when creating new widgets we can provide them as the data_function argument shown above.

Now comes the tricky part - we can externally change the slice_func and all the data_functions (now safely tucked inside closures) change their behaviour by using the new slice_function since variables inside closures are pointers rather than copies.

Magic!

We have reached a situation where all code is tucked neatly inside closures. The closures themselves have no knowledge of the outside world, there are no flags they need to check, no external data anywhere. All they care about is running the data function and doing their thing.

And yet, through the magic of closures, we get to globally change their behaviour without worrying about internal state or having to call a specific function to do something on an object.

To me this feels cleaner than any abstraction object oriented programming has ever come up with.

Enhanced by Zemanta

Did you enjoy this article?

Published on March 14th, 2012 in closures, functions, JavaScript, jQuery, Languages, Plug-in (computing), Programming, Uncategorized

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet 📖

Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️