Intermediate(ish) Javascript: Quick Intro to Bind & Currying

Mike (Nongaap)
nongaap
Published in
2 min readJul 29, 2016

Preface: In the spirit of my “Tech 101 Valuations” posts I’ve decided to write a quick post on bind() and how to use it to curry functions…This is a slight…ok major…departure from my typical posts on tech, finance, and valuations but I felt it was important to share my software development learnings the same way I’ve shared my finance learnings. (The story behind how I ended up taking this software development journey will be for another time.)

Bind & Curry: All javascript functions are bound to an object and if you’re not explicitly setting the ‘this’ object for your function it will be done for you. For example, invoking a function hello(“world”) is equivalent to invoking hello.call(window, “world”). (Note that call is a way to explicitly attach a function to an object)

It’s important to note that even when you’re not explicitly setting your function to an object, Javascript is attaching the object for you “under the hood”. In many cases this implicit attachment ends up being the global window object instead of the object a software developer originally intended.

To avoid accidently having the ‘this’ object set to window, you can use bind() (or call() and apply()) to explicitly point a function’s ‘this’ to specific objects.

A key difference to using bind() vs. call() or apply() is that you’re able to invoke a function that uses bind() in the future (vs. immediately invoking using call() and apply()) and avoid using stale arguments. Additionally, bind() can be used to curry a function (curry is a way “pre-set” the arguments passed into a function).

For example, if you had a function addFive(number) that adds 5 to any number you pass in, you can curry the function by passing in a value when binding it to a new object.

var fifteen =addFive.bind(newObject, 10)

By pre-setting the argument to 10, fifteen will return a value of 15 (i.e. 5 plus the pre-set 10 value) no matter what value is subsequently passed into fifteen as an argument. If you did not curry the function, function would add 5 to any number you pass in!

--

--

Mike (Nongaap)
nongaap

Ex-Activist Investor. Ex-JavaScripter. Current: http://nongaap.substack.com. Mostly tweet about tech, governance, strategy, board dynamics, & art of corp war.