In traditional object-oriented languages, x = x + 1
is a simple and legal expression. But in Functional Programming, it's illegal.
Variables don't exist in Functional Programming. Stored values are still called variables only because of history. In fact, they are constants. Once x
takes a value, it's that value for life.
So, if a variable is a constant, then how can we change its value?
Functional Programming deals with changes to values in a record by making a copy of the record with the values changed.
For example, instead of doing:
var numbers = [1, 2, 3];
numbers[0] += 1; // numbers = [2, 2, 3];
You do:
var numbers = [1, 2, 3];
var newNumbers = numbers.map(function(number) {
if (numbers.indexOf(number) == 0)
return number + 1
return number
});
console.log(newNumbers) // prints [2, 2, 3]
And there are no loops in Functional Programming. We use recursion or higher-order functions like map
, filter
and reduce
to avoid looping.
Let's create a simple loop in JavaScript:
var acc = 0;
for (var i = 1; i <= 10; ++i)
acc += i;
console.log(acc); // prints 55
We can still do better by changing acc
's lifetime from global to local:
function sumRange(start, end, acc) {
if (start > end)
return acc;
return sumRange(start + 1, end, acc + start)
}
console.log(sumRange(1, 10, 0)); // 55
No variables or loops mean simpler, safer and more readable code (especially when debugging or testing - you don't need to worry about the value of x
after a number of statements, it will never change).