5 Just Enough JS
Basics: IDVW, pp. 36-52
Before JavaScript ES6, the ‘var’ keyword was used to declare a variable. Variables declared using the ‘var’ keyword are either globally or functionally scoped, they do not support block-level scope. Therefore, in JavaScript ES6, the ‘let’ keyword and ‘const’ keyword were introduced.
The ‘let’ keyword deals with a block scope. It can be reassigned but cannot be redeclared.
The ‘const’ keyword is also blocked scoped. It cannot be reassigned and cannot be redeclared.
As a general rule, you should always declare variables with ‘const’, if you realize that the value of the variable needs to change, go back and change it to ‘let’.
For more detailed information regaring ‘var’, ‘let’ and ‘const’, please see Difference between var, let, and const keyword in JavaScript
objects, arrays, arrays of objects, functions (and other things)
5.2 Arrays of objects
// Try me in the Console
const object_dataset = [
{cx: 100, cy: 150, fill: `red`},
{cx: 200, cy: 100, fill: `blue`}
];
d3.select("svg#objects")
.selectAll("circle")
.data(object_dataset)
.enter()
.append("circle")
.attr("cx", d => d.cx)
.attr("cy", d => d.cy)
.attr("r", "30")
.attr("fill", d => d.fill);
See also: JavaScript Array of Objects Tutorial
5.3 .map()
What’s the issue?
In R many operations are vectorized:
## R output ## [1] 1.732051
## R output ## [1] 1.732051 2.236068 2.645751
Not so in JavaScript:
5.3.1 Simple arrays
Use .map()
to operate on each array element separately. The concept is similar to lapply()
or purrr::map()
, but unlike in R, it’s needed for simple arrays.
R
## R output ## [1] 1.732051 2.236068 2.645751
JavaScript
Do something to every element of a simple array:
R: Sum two arrays
## R output ## [1] 5 7 9
JavaScript: Sum two arrays
5.5 D3 statistics
D3 brings us back to familiar ground with functions that take an array and return a single value. Here are D3 functions with the same names and behavior as their R equivalents:
R | D3 |
---|---|
min(x) |
d3.min(x) |
max(x) |
d3.max(x) |
sum(x) |
d3.sum(x) |
mean(x) |
d3.mean(x) |
median(x) |
d3.median(x) |
A few with different names:
R | D3 |
---|---|
range(x) |
d3.extent(x) |
var(x) |
d3.variance(x) |
sd(x) |
d3.deviation(x) |
d3.quantile()
takes a single value for p
, not an array as in R. (In earlier versions of D3 it was necessary to sort the array before finding quantiles, but this is no longer the case.)
R | D3 |
---|---|
quantile(x) |
d3.quantile(x, p) |
Thus for a single quantile we have:
5.6 D3 + .map()
D3 statistics functions combined with .map()
can be helpful in a variety of situations.
Vectorizing a parameter, for example to mimic quantile(x)
in R:
R
## R output ## 0% 25% 50% 75% 100%
## R output ## 1.00 17.50 38.50 64.75 90.00
JavaScript
Sum up the first item of all elements in an array of arrays:
R
## R output ## [1] 400
JavaScript
Sum up all items in each array to create a simple array:
R
## R output ## [1] 340 470
JavaScript