Javascript closures and side effects in plain English? (separately)

alexchenco picture alexchenco · Nov 14, 2011 · Viewed 20.5k times · Source

I've been reading some JavaScript books and I always hear about closures and side effects. For some reason I can't understand what they really are. Can anyone explain to me what they are in plain English plus examples? (as you were explaining it to someone with the programming level of a graphic designer).

Answer

Larry OBrien picture Larry OBrien · Nov 14, 2011

Side effects are the easier concept. A "pure function" is a function that maps its input value(s) into an output value function plus(x, y) { return x + y; }. A "side effect" is any effect other than that return value. So, for instance:

function plusWithSideEffects(x, y) {
  alert('This is a side effect'); 
  return x + y;
} 

has the side effect of raising an alert dialog (and requiring user interaction). Every code function has some side effects (they all consume memory and take time, if nothing else), but when people talk about side effects, they are often most concerned with either IO (like the alert dialog above) or the writing of state that lives beyond the execution period of the function.

The challenge with side effects is that they make functions harder to reason about and to reuse. (It's much easier to reason and reuse functions that are as close to "pure functions" as possible, since they tend to "do one thing well.")