Using ES6 with D3.js
Getting set up
I recommend using the cli tool if you are comfortable with the terminal.
this might not work the way you expect when using arrow functions. If you need to reference the element inside the function (e.g.
d3.select(this)) you will need to use a normal anonymous function.
Let and Const
Instead of using
var for variables you can be more explicit about the type of variable you want.
let works the same as
var but it’s block scoped. If you use it inside an
if statement, it won’t be accessible outside the block.
const is like
let but once it has been assigned a value it can’t be reassigned.
One of the nice things about d3.v4.js is that it is broken up into modules. Because D3 modules don’t export a default object, you’ll need to use this star syntax to import everything in the module (HT Mike). Importing D3 as modules is especially useful if you are using D3.js in the context of a larger application.
Destructuring is a useful way of extracting data from objects and arrays. In this example i’m creating a constant named blue, that is assigned to whatever
You can abbreviate methods in ES6. Instead of writing an anonymous function that’s assigned to a key, you can put parenthesis and a block statement around a method name.
You can set a parameters default value by adding an equal sign and then the value you want as the default. If the function is called without the parameter, or with the parameter set to
undefined the default value will be assigned.
There’s a lot more to ES6 than what I showed here but if you’re looking to get started, give these examples a try. Once you start using the new syntax, it’s hard to go back!
If you liked this post, you should check out my full course on D3. You can read more about it below and sign up for a free lesson!