Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I think it's mostly a stylistic choice, but getting in the habit pays dividends in that it makes it easy to do certain list related actions in a consistent way. forEach doesn't necessarily show this off well, but filter and map make it more obvious.

E.g.

   // Get list of even squares of first 10 integers
    Array.from({ length: 10 }).map((e,i)=>i*i).filter((i)=>i%2==0).forEach((i)=>console.log(i));
    // Or more readable
    Array.from({ length: 10 })
     .map((e,i)=>i*i) // Get squares of each number
     .filter((i)=>i%2==0) // filter for evens
     .forEach((i)=>console.log(i)); // print
Want to filter or manipulate the values in a different way? Throw in another map or filter. Want to pass complex values between steps? You can pack them into an array or object in a map and unpack later.[1] Once you're used to doing stuff with lists, you can use some other interesting list operations like reduce(), some(), every(), etc.

It's not really better (it's subjective), it's just different and a lot of people are used to it and prefer it (and it's fairly consistent in nomenclature across some languages, which is a bonus).

1: https://en.wikipedia.org/wiki/Schwartzian_transform



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: