Wednesday, 29 August, 2018 UTC


Summary

One of the annoyances of old-school JavaScript was side effects; then Array.prototype got methods like filter, map, and forEach so we didn’t need to burn variables before looping over values.  I can’t explain how happy I am that the JavaScript language continues to evolve.
Every once in a while I need to filter an array by not its original value but instead a new value, so I use map:
myArray.map(item => {
    // Do whatever processing...

    // If we don't care about the item, return false or null or undefined
    return false;
});
While I get the new values I want, sometimes if an iteration returns a result I don’t want, I return null or false, which is great, but then I’m left with a bunch of useless items in the resulting array.  The next step is using filter, in which case I could do:
myArray
    .map(item => {
        // ...
    })
    // Get rid of bad values
    .filter(item => item);
Since the values I don’t want aren’t truthy, the filter above removes those bad items.  Did you know there’s a clearer way with Boolean?
myArray
    .map(item => {
        // ...
    })
    // Get rid of bad values
    .filter(Boolean);
If the value isn’t truthy the item is filtered out and I’m left with only the items I want!
The post Array and Boolean appeared first on David Walsh Blog.