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;
 }
});
Talespin_Kit
  • 20,830
  • 29
  • 89
  • 135
  • 1
    Not really, you probably want `map` not `every`. – elclanrs Nov 15 '14 at 10:11
  • Why not? You can modify array values in `some` and `every`. You can as well delete values, and methods will still work as expected. In fact both methods are designed to support that behavior. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.17 However in your example you should not use `every` you should use `map`. – dfsq Nov 15 '14 at 10:13
  • 1
    If you gonna use `map`, `filter`, etc... you might as well avoid mutation, and carry on as I think that's the style it calls for. If I need to "modify" the array and no methods help, then I'd use `reduce` with a brand new accumulator. – elclanrs Nov 15 '14 at 10:17
  • Using a for loop seems pretty legit for this use case, unless you actually need the old version of the array as well. Just saying – Niklas B. Nov 15 '14 at 10:25

2 Answers2

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.)

Community
  • 1
  • 1
g.kertesz
  • 434
  • 3
  • 10
  • It depends on the siutation (for this specific example, `map` is the more idiomatic function to use), though in general if you want to edit the array from your function, you're probably better off with `forEach`. Also, `forEach` isn't a jQuery method, so `this` refers to the global object or undefined in strict mode. – Qantas 94 Heavy Nov 15 '14 at 10:43
  • @Qantas94Heavy, you are absolutely right that `this` can not be used in the callback. I will edit my answer. I disagree however on using `map` as its intention is to create a new array, which is not what OP wanted. – g.kertesz Nov 15 '14 at 15:05
0

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).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375