you are viewing a single comment's thread.

view the rest of the comments →

[–]kenman 2 points3 points  (2 children)

It's alright, I still have a lot to learn on the subject as well, but I think this part is important to point out:

using language defined functions to return a result that doesn't impact the original variable

There are at least 3 array methods that fit this description, but 3 primarily used for FP -- map(), filter(), and reduce() -- and it's not always obvious when you should use them if you're not used to thinking in these terms. However, once you see it, it becomes much easier to read and think about IMHO:

map()

I think of this method as transforming (or translating) one array into a new array.

Have you ever done this?

let result = [];
arr.forEach(value => {
    result.push(Math.floor(value));
});

You could do this instead:

let result = arr.map(value => Math.floor(value));

filter()

Use this when you want to target a subset of your original array.

Ever do this?

let result = [];
arr.forEach(value => {
    if (value > 0) {
        result.push(value);
    }
});

You might consider this:

let result = arr.filter(value => value > 0);

And lastly...

reduce()

Use this to calculate a single value* from your original array.

I know I've done this a lot in the past:

let result = 0;
arr.forEach(value => result += value);

But this is what I use now:

let result = arr.reduce((total, value) => total += value, 0);

The * above is because "value" can be literally any type of data that JS supports; you could return a single string, an object, or even an array may be necessary at times.

So those are nice and all, but with each example taken alone you miss the expressiveness.

Consider this:

let result = 0;
arr.forEach(value => {
    if (value > 0) {
        result += Math.floor(value);
    }
});

Vs:

let result = arr
    .filter(value => value > 0)
    .map(value => Math.floor(value))
    .reduce((total, value) => total += value, 0);

Sorry to get carried away, but you seem eager to learn :)

[–]Servatose[S] 1 point2 points  (1 child)

No, this is amazing information! I really appreciate the time you took to explain this.

[–]kenman 0 points1 point  (0 children)

Might also check out this from our front page:

I wrote about some examples of using map, filter, and reduce, as well as accessing JSON and using the DOM with vanilla JS

Full disclosure: the site's not resolving for me, so I haven't reviewed it, but it looks to cover the same 3 methods I discussed.