Skip to content

Functional Programming

JavaScript function variables don't have to be anonymous

If you’ve used JavaScript much, you’ll probably know one of its very convenient features — the ability to assign functions to variables, send them as arguments, and return them as values. This lets you write code like this, where functions themselves return other functions: {% codeblock lang:javascript Anonymous function bonanza %} /* This code creates a basic ‘curry’ function (see my earlier post for an explanation) It relies heavily on function variables. */ var add = function(x, y) { // <- A function variable return x + y; }; var curryUtil = { curry : function(functionToCurry, x) { // <- A function object property return function(y) { // <- A function return value return functionToCurry(x,y); }; } }; var add7 = curryUtil.curry(add, 7); add7(3); // returns 10 var double = curryUtil.curry(function(x,y){ // <- A function literal argument return x * y; }, 2); double(8); // returns 16 The problem with this, however, is that all the functions in the above example are anonymous &mdash; they aren't named. Beyond making your code more obscure than it needs to be, this also makes debugging them a problem , because when you look at the browser's call stack, you're going to get something like this: {% img center /images/2014/callStackAnonymousFunctions.png Now they're all named! %} Yeah. Good luck with that. However, you can remedy the issue quite easily &mdash because JavaScript lets you name your function variables: {% codeblock lang:javascript Named function variables %} var myFunction = function myFunction(x) {...} var myObject = { myMethod : function myMethod(x) {...} }; function returnSomeFunction() { return function myReturnedFunction() {...} } …name your function values…

Read more →

June 21, 2014

JavaScript curry

If you’ve had much exposure to functional programming, you might have heard of ‘currying’. This funny term refers to a kind of functional composition: taking a function that takes two (or more) parameters, and turning it into a function that takes less parameters, and automatically applies the other arguments, which have been ‘baked’ into it. For example, let’s say we have an ‘add’ function - function add(x,y) { return x + y }. I might have an instance where I want to add various numbers to a constant - say, 7. Rather than constantly calling add(7, x), currying lets me create an ‘add7’ function. Whatever I pass, add7 always adds seven to it.

Read more →

May 11, 2014