Back to Posts

Write better functions in Javascript

I see this over and over again ( especially in Angular 1.x ) code and it goes something like this:

var name = 'Nik';

function doStuff() {  
  var newName = name + 'what ever we want';
}

This is wrong and people who are new to the industry tend to do this quite often. They change values all over the place. Let's fix this and introduce a concept called pure functions.

I've noticed JS community is talking more and more about functional programming concepts and pure functions is one of them. I really love the idea of functional and oop programming smashed together to bring the best out of both worlds but thats for another post. So here is one way to define a pure function:

Pure functions don't depend on and don't modify the state of variables out of its scope.

That means that a function should not worry and change anything that's in the outside world but only worry about the stuff that it does. So how would we write the previous doStuff() function in a pure way ? Here it goes:

function doStuff(param) {  
  var newParam = param + 'what ever we want';
  return newParam;
}

That function is better because:

  • Its resuable.
  • Its independent. It does not depend on a situation that's happening around it ( like the previous version did on the variable name, where you had to have that variable in order for a function to do its work )
  • Its more testable. You can easily isolate and unit test it.

And there we go. A simple change but it means so much when you have a project at scale and when things can get hairy if you have functions that are coupled with everything else and are not pure.

Fellow readers let me know what you think about the post on the internetz, twitterz and redditz :)

Software engineer that loves business side of things as well. Also lifts a lot of weights.

Read Next

AngularJS with Rails 4.2.5