Pitfalls
Common pitfalls writing JavaScript in R#
The examples below use the following options
in the source_r function call. Under this setting, R functions are not
loaded into the environment.
1. JavaScript uses 0-based indexing#
2. Undeclared variables are created in the global environment#
While directly accessing and modifying global variables are not uncommon in JavaScript visualisations - as we will see when we use p5.js in the other articles - it is best to use it only when it is necessary. Here is how one declares a variable before using it:
note
If you use default_2_deparsers() (introduced in version 1.1.0), then
sketch will automatically declare the variable for you.
3. return in JavaScript function must be explicit#
If you use default_2_deparsers() (introduced in version 1.1.0), then
sketch will automatically handle return for you.
4. JavaScript function reads argument by position / order#
Note that since JavaScript does not use named argument, y = 3 and
x = 1 are actually interpreted as assignments! Both assignments will
happen before the function first is called.
But don’t worry, this won’t be a problem in sketch as it will strip
off all the names during the transpilation, i.e. first(y = 3, x = 1)
gets transpiled into first(3, 1). The design decision rules out the
use of in-place assignments, but it guards against unintended ones.
5. JavaScript passes objects by reference (think of R6 in R)#
6. A browser session has a pre-populated namespace#
For example, the variables document, window, location, var,
stop, open, focus are taken already. Avoid assigning values to
these variables!
The full list can be found with the following code: