Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    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.

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

    Did you enjoy this article?

    Continue reading about Closure and currying magic for cleaner javascript

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

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

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    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 ❤️

    Created by Swizec with ❤️