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?
f
is also the creation of new state (a new activation with new parameters), whether multiplef
's are sequentially invoked, or there is recursion involved, each invocation off
is the conjuring of new state. So, parameters withinf
, as well as local variables withinf
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