An ES6 primer

This article is part of my series Visualization with React. Previous article: React and D3 – similarities and differences

In this guide, I will use ES6 notation whenever I would normally do it in my day job. There are many, many differences in ES6 compared to previous versions of javascript and that can be daunting. But in this time and age, a lot of code you can run into is going to be written in ES6, so a cursory knowledge of some of its features can go a long way.
Here are the features I use most often:

Fat arrows functions

ES6 introduces a new, more concise way to write functions. Instead of writing:

function add10(d) {return d + 10;}

one can write:

var add10 = d => d + 10

Technically, those two forms are not completely equivalent. The main difference is if you need to use the context keyword this. But in most cases, fat arrows are a much more concise, and therefore more legible syntax.

To do a function which takes more than 1 argument, wrap them in parentheses like so:

(a, b) => a + b

For a function with several statements, you must use curly braces like a regular function, and use return if needs be:

d => {
  return d;

For a function that returns an object, wrap that object in parentheses to avoid confusing it with the previous form:

d => ({key: d})

const and let

Before ES6, to declare variables, you could only use the var keyword.

var a;
var b = 10;

In ES6, you can declare variables using const or let. When you use const, the variable cannot be reassigned:

 const a; // error - a must be assigned a value 
 const b = 1;
b = 2; // error - b can no longer be reassigned

Variables declared with let can be reassigned.

 let a; // ok
a = 10; // ok
a = 20; // still no error

const and let are more expressive than var, because they specify whether we plan to change the value of a variable or not. They have another advantage: they are scoped. They can be used inside of an if branch, or a for loop, and not be accessible outside of it. Conversely, var are not scoped – they are available everywhere within the function where they are declared, or globally if declared outside of a function.
So, there’s no reason to ever use the var keyword in ES6.

Spread operator

In ES6,if you have an array inside another array, you can replace that array with its items in sequence using the spread operator. An example would make this clearer:

const a = [1, ...[2, 3, 4]]; // [1, 2, 3, 4].

That may seem like not much but it’s super versatile and useful. For instance, instead of concatenating two arrays, you can write:

const a = [1, 2];
const b = [3, 4]
const c = [...a, ...b]; // [1, 2, 3, 4]

Interestingly, it works with empty arrays:

const a = [1, 2];
const b = [];
const c = [...a, ...b]; // [1, 2]

But not with primitive literals (numbers, etc)

const a = [1, 2];
const b = 3;
const c = [...a, ...b]; // error

Instead of pushing an item to the end of an array, you can also use the spread operator:

const a = [1, 2];
const b = 3;
const c = [...a, b]; // added benefit - creates a new array instead of changing it in place.

Note the difference between these 2.
[…[1,2], 3] will work;
[…[1, 2], …3] will not.

Composing arrays like this can be conditional!

const a = [1, 2];
const b = 3;
const condition = false;
const c = [...a, ...(condition ? [b] : [])] // [1, 2];

What just happened? just like above, but we applied the spread operator to the expression which is in parentheses. If the condition were true, that expression would be equivalent to [b]. But since it’s false, it is equivalent to an empty array.

An experimental feature of ES7 extends the spread operator to objects.

const obj = {key: 'a'};
const newObj = {...obj, value: 1}; // {key: 'a', value: 1}

Destructuring assignment

You can do more stuff with objects in ES6. Destructuring assignment covers a number of nifty features but here are the two I use the most.

const obj = {key: 'a', value: 123};
// you can read several properties from an object at once and assign them to variables:
const {key, value} = obj;
console.log(key, value); // 'a', 123

Before ES6, you had to write a function like this:

function div(num, den) {return num / den;}
div(6, 2); // 3;
div(2, 6); // 0.333333 order of the parameters matters!
div(3); // NaN - can't forget an argument! 

In ES6, we can expect the function as argument to take an object and access its properties:

function div({num, den = 1}) {return num / den;}
div({num: 6, den: 2}); // 3
div({den: 2, num: 6}); // still 3
div({num: 3}); // still 3 - den has a default value

Using an object, we don’t have to remember in what order the function parameters have to be provided.

Wrapping it all together

what’s another form for the last function I wrote?

const div = ({num, den = 1}) => num / den;

In the next article in the series, Coding with React, we will finally start to write some React code.


D3 and React – similarities and differences

Previous article: Visualization with React

d3, meet cousin React

Let’s not sugarcoat it: working with React is more complicated than with plain vanilla javascript. There are a few additional notions which may sound complex. But the good news is that if you come from the d3 world, there are many concepts which are similar. Visualization on the web is, at its core, transforming a dataset into a representation. That dataset is probably going to be an array, and at some point the framework will loop through the array and create something for each element of the array. For instance, if you want to make a bar chart, you probably will have at some point an array with one item that corresponds to each bar, which has a value that corresponds to its length. Looping through the array, each item is turned into a rectangle whose height depends on that value. That logic, which is at the core of d3 with selections, is also present in React. In d3, visualizations are essentially hierarchical. We start from an SVG element (probably), add to it elements like groups, which can hold other elements. To continue with our bar chart example, our chart will have several data marks attached to it (the bars), and there’s a hierarchical relation between them: the chart contains those marks. Our chart could be part of a dashboard that has several charts, or part of a web page that has other information. At any rate, in the d3 world, everything we create is added to a root element or to elements we create and arranged in a tree-like hierarchy. This is also the case in React, with a difference: the world of React is mostly structured into components. When that of d3 is mostly made of DOM elements like HTML or SVG elements, that of React is made of components. A React component is a part of your end result. It can be as small as a DOM element, or as big as the whole application. And it can have component children. So, components are logical ways to package your application. Components are created with modularity and reusability in mind. For instance, I can create a bar chart component in React, and the next time I have a bar chart to make, I can just reuse the exact same component. I can also create components to make axes or the individual bars in the chart, which my bar chart component will use. But the next time I need a bar chart, I wouldn’t have to think about it. In contrast, if I want to create another bar chart in d3, I probably have to recreate it from scratch and decide manually what happens to all the SVG or HTML elements that constitute the bar chart.

You say dAYta, I say da-tah

One fundamental way in which d3 and React differ is by how they treat data. If you read about React, you may find fancy terms like one-way data binding. In how many ways the data is bound in d3 is not something which is on top of our head when we create visualization so that might sound confusing. In d3, an element can modify the data which is associated to it. I’ve used it so many times.

See the Pen React simple scatterplot by Jerome Cukier (@jckr) on CodePen.

These bars have been made with a very simple dataset shown below them. If you click on the bars, the underlying data will change and the representation will change as well. In the world of React, when properties are passed to a component, they cannot be changed. That’s what one-way binding means. Data in React flows unidirectionally. Once it’s defined, it determines the way all components should be displayed. In certain events, a parent component can pass different properties to its children component and they may be re-rendered (we’ll see this in just a moment). But the important part is that properties passed to a component can never be changed. You may wonder: why is that even a good thing? React makes it impossible to do things! yes, but in the process it also makes things much safer. If properties can’t be changed, it also means that they can’t be altered by something we hadn’t thought of. Also, it makes it much easier to work on components independently: one team mate could make a bar chart component while her colleague makes a line chart. They don’t really need to know the inner working of the other component, and they know that nothing unexpected will disturb the way their component function.

The state of affairs

Components of React have a really powerful feature which doesn’t explicitly exist in d3: the state. The state represents the current status of a component. Here’s a simple switch component:

See the Pen React simple scatterplot by Jerome Cukier (@jckr) on CodePen.

We want to record the fact that the switch can be turned on or off. Here’s how it should work: First we create our switch component, and it’s supposed to be off. Then, if the user clicks it, it becomes on if it were off and vice-versa. And it should also be redrawn, to reflect that it’s been turned on (or off). The state does all that. It records the current status of the component. Technically, it’s an object with properties, so it can save a lot of information, not just a simple true or false value. The other great thing about the state is that if it changes, then the component is re-rendered. Rendering a component could require rendering children component, and they may be re-rendered as well. So with the state and properties, we have a powerful framework to handle events and whatever may happen to our app. If there’s an event we care about, it can change the state of a component, then, all of the children components may be re-rendered. And there’s no other way to redraw them. This is in contrast with plain d3 where anything goes – anything can change anything, data can be used to render elements, the underlying data can be changed without changing the element, the element can be transformed without changing the underlying data.

State is an important notion in computer science. In d3, it’s just doesn’t have a more formal representation than all the variables in your code.

In the next article in the series, an ES6 Primer, we will look in some useful ES6 features for React.


Visualization with React

Some back story…

In what seemed a lifetime ago now, I wrote tutorials to help people get started with Protovis as I learned it myself (it is indeed a lifetime away since Protovis is dead and buried for all intents and purposes). And a few years ago, I did the same for d3 as this started to become the most powerful visualization framework and for which documentation was still scarce. I wrote these tutorials to help me learn, but since then I have met many people who found them useful which blew my mind. By documenting my learning, I got noticed by Facebook and travelled 9000 miles to a new life.

At Facebook, I had some loosely-defined data visualization explorer role. While I joined during the infancy of React, I didn’t feel super comfortable using it then – I felt more effective writing one-off d3 applications. Eventually, I moved on and am now working at Uber as a fully-fledged data visualization engineer. I work almost exclusively with dashboards, which have a pretty elaborate UI.

Like in many other companies, at Uber, we use React for our web applications, including our visualizations, dashboards and maps. Increasingly, React is becoming the lingua franca of visualization: more than a tool that allows one to draw data, a mindset that informs how one should think a visualization. React is no longer a young library – the initial public release dates back from May 2013, and its very first application at Facebook was visualization (my first Facebook project, pages insights). There’s already many, many learning resources and tutorials for React. What I’ll try to do here is to show how React can be used for visualization: hopefully, this will be useful both for people who come from d3 and who’ve never worked with a web framework before, and for people who are familiar with React but who don’t know visualization well. That won’t be a complete and exhaustive guide, more a way to get started with references on how to go further.

The articles

I’ve structured this guide in 7 parts, and I’ll publish one per day:

  1. React vs D3, where we’ll explore similarities and differences between these two frameworks.
  2. An ES6 primer. I have written all the examples in good, sensible, modern ES6 javascript, because as of 2016 this is probably the most common syntax. Without going too deep into the details, I’ll explain what parts of the language I used for the examples, and how they differ from ES5.
  3. Gentle introduction to coding with React, where we’ll explore the high-level concepts of the framework and see how we can create visual elements from data. We’ll end on a presentation of JSX, a flavor of Javascript used to write React applications, which I’ll also use for most of the examples for the same reasons as ES6 – because it’s the most widespread way of writing React code today.
  4. React components, the most important concept in React and the building blocks of React applications.
  5. Beyond rendering. We’ll look at the React concept of lifecycle methods, and also how we can use d3 within React components.
  6. Creating a React visualization web app – using what we’ve seen, and two libraries – Facebook’s create-react-app and Uber’s React-vis, we’ll create a small standalone React visualization that can be deployed on its own website.
  7. The big leagues – in that last part, we’ll write together a more complex visualization with live data and several components interacting with one another.

The code

The examples of parts 1-5 can be found on codepen. I’ll add link to examples of part 6 and 7 when they go live.