1

I've been learning functional programming in javascript of late, and there's one thing that's been confusing me. I can't quite understand if it's ever okay to redefine variables.

Something like: a = a + 1 immediately throws up red flags. a is mutating, so that's a no go. And certainly declaring a variable like so: var a = 10 is fine, after all we're just giving the state 10 a name. But what about something like this:

function f(x){
  var y = x;
  return y + x;
}
/*overlooking the fact that this code
has no meaningful purpose and could be
simplified as return 2 *x;*/

Is that allowed? Declaring variable y is fine, but what if we call f(x) twice? How about writing this statement with recursion? Is redeclaring variable y multiple times okay? Or is y just a variable that exists solely during the time that it's nested function is running.

While I was looking for the answer to this question, I came across a page about pure and impure functions. I take it that purity isn't functional programming exclusive. Further digging told me that declaring variables within a function could potentially lead to impurity. So even if I could declare variables within the scope of a function, would that be problematic? What rules do I need to adhere by to avoid compromising the purity of my functions?

  • When programming functionally, you are always allowed to create new state, whether as simple as a local variable or as complex as whole data structures (or both). You just shouldn't modify already existing state. – Erik Eidt Sep 29 '16 at 16:03
  • Further, an invocation of f is also the creation of new state (a new activation with new parameters), whether multiple f's are sequentially invoked, or there is recursion involved, each invocation of f is the conjuring of new state. So, parameters within f, as well as local variables within f are new to each invocation. Thus, invoking a functions is the creation of new state, which is allowed when programming functionally. The creation of new state is required to get things done functionally, since you cannot modify existing state! – Erik Eidt Sep 29 '16 at 16:06
2

Your example is fine, because it is a new y in each invocation of the function. A simple rule is "appears on the left of = exactly once, at the point of declaration".

Function "purity" is generally in reference to a lack of side effects, that is affecting anything outside of the function (e.g. incrementing a global counter, writing to a file, etc).

function impure(x) {
    x.y = 10; // Modifying x here
    return x.y * 5;
}

function pure(x) {
    var y = 10;
    return x + y + 5;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.