The following code works. But is it the right way to modify an array value within the functional-programming styled methods.
a = [1, 2, 3];
a.every(function(val,index, arr) {
if (val === 2) {
arr[index] += 1;
}
});
The following code works. But is it the right way to modify an array value within the functional-programming styled methods.
a = [1, 2, 3];
a.every(function(val,index, arr) {
if (val === 2) {
arr[index] += 1;
}
});
No. Though your code works, conceptually you should use the forEach
method instead, see here.
(Also, for readability, drop your arr
argument and use this
.)
But is it the right way to modify an array value within the functional-programming styled methods.
No. With the functional programming paradigm you should not modify any objects (regardless of what method you use). Better:
var a = [1, 2, 3];
var b = a.map(function(val) {
return (val === 2) ? 3 : val;
});
Notice that using every
like you did makes no sense - you are not interested in testing a predicate on all elements. When you really want to carry out side-effects from your callback, you should use forEach
(which is not very functional, but at least makes your intention clear).