Two Useful JavaScript Pointers

Posted on November 10, 2018
    > Epistemic status: This is erm... a technical post. 

JavaScript, while a sometimes hard to deal with language, does have some features as of late, mainly from ES6, that make the language nicer to deal with. Here are two examples that I have found particularly useful, and hopefully should prove useful to others as well.

FlatMap

A relatively new functional programming feature in JavaScript is the flatMap function. As in the name, it not only applies a mapped function to an array, but it also flattens the array as well. In other words, it is a combination of the .flat() function and the .map() function. For example, look at this code snippet below:

While what this does is simple, instead of with map each result becomes an array, the array turns a single array with all the values in it getting the mapped function applied to it. As stated in the function name, the array is not only getting mapped, but flattened as well. Another example is combining arrays filled with strings into a single array. First above the usual map, and then the usage of flatMap instead:

As seen, unlike with the usual map function, the array is flattened, making the data is easier to work with then in general. This function is useful for working with GeoJSON data and making sure the data is flat and not nested.

For example, I was working with a CSV sheet and the rows were roughly filled like this:

While usually I could use Regex to clean this up, turns out flatMap also does a good job of converting the data into the format I wanted. As seen below:

Now the data is much easier to work with when it comes converting the values into GeoJSON points to put on a map.

ES6 and D3.js

D3.js is a famous and useful library for creating data visualizations in the browser. With ES6 in most browsers, some of the benefits of modern syntax can be used to make D3.js code easier to read and less sprawling.

To give an example, instead of writing out a whole function for the .attr() function, arrow functions can be used instead! An example below:

Instead of writing out a complete function(d, i){...}, the usage of arrow functions can keep the code on a single line.

Another way ES6 makes D3.js programming easier in general is the usage of template literals. Instead of doing the usual JavaScript method of chaining + signs together to concatenate strings, one can use template literals to run JavaScript code when for example, setting styles.

To again give an example, here are some template literals being used in the context of adding styles to elements:

In general, much cleaner then having a mess of "" and + signs everywhere.

Hopefully these examples might prove helpful to others.