Just because functions are first class objects, there are closures, and higher order functions, does Javascript deserve to be called a Functional Programming language? The
What I really hate in javascript (if You try to look at it as FP language) is this:
function getTenFunctionsBad() {
var result = [];
for (var i = 0; i < 10; ++i) {
result.push(function () {
return i;
});
}
return result;
}
function getTenFunctions() {
var result = [];
for (var i = 0; i < 10; ++i) {
result.push((function (i) {
return function () {
return i;
}
})(i));
}
return result;
}
var functionsBad = getTenFunctionsBad();
var functions = getTenFunctions()
for (var i = 0; i < 10; ++i) {
// using rhino print
print(functionsBad[i]() + ', ' + functions[i]());
}
// Output:
// 10, 0
// 10, 1
// 10, 2
// 10, 3
// 10, 4
// 10, 5
// 10, 6
// 10, 7
// 10, 8
// 10, 9
You need to understand JS stack environment (I don't if it is the right term) to understand such a behavior.
In scheme for example You just can't produce such thing (Ok, ok -- with the help of underlying languages' references You can make it):
(define (make-ten-functions)
(define (iter i)
(cond ((> i 9) '())
(else (cons (lambda () i) (iter (+ i 1))))))
(iter 0))
(for-each (lambda (f)
(display (f))
(newline)) (make-ten-functions))