Difference between properties and accessors in Nashorn Javascript Engine
Summary: in the JavaScript snaps, what is the difference between doc.get(“something”) and doc[“something”] ??
Details and Background:
I am very well-versed in C++, SQL, and a smattering of other languages, and have been developing for a long time. But I am only a pedestrian Javascript programmer at best.
We have a lot of Javascript snaps that were written by an offshore team. I regularly see stuff that seems confused or random to me, for example:
execute: function() {
this.log.info("Executing Transform Script");
while (this.input.hasNext()) {
var doc = this.input.next();
for (var i = 0; i < doc.get("Whatever").length; i++) {
var numThings = doc["Whatever"][i]["Things"].length;
for (var j = 0; j < doc["Whatever"][i]["Things"].toArray().length; j++) {
var foo = doc["Whatever"][i]["Things"]["something"];
// do some work
}
...
When I’ve asked some of these developers why they used doc.get("Whatever")
and what it does, I get uninformative answers such as “it gets the Whatever property” (duh!) or “well, that’s just how you have to do it.” (Oh, really? Why?)
I get the same kind of non-answers for the reason why there is a call to .toArray()
method in line 7 above, but not one in line 6.
Reading online hasn’t helped me much, because every example seems to refer to newer versions of Javascript than what we use in SnapLogic.
In the Nashorn engine (and our Javascript snaps specifically):
- If the
Things
property is sometimes an array and sometimes a scalar, would the lack of.toArray()
cause the script to fail? - If
Things
is sometimes completely absent, do either of the options shown offer any protection? (I’m guessing not, and that you’d need to checktypeof
for'undefined'
.) - Does the
.get()
provide any additional safety (or do anything else beyond what doc[“Something”] does)? - Let’s assume the arrays shown above are always arrays. Could someone just as easily (and more clearly) have written the following?
execute: function() {
this.log.info("Executing Transform Script");
while (this.input.hasNext()) {
var doc = this.input.next();
for (var i = 0; i < doc.Whatever.length; i++) {
var numThings = doc.Whatever[i].Things.length;
for (var j = 0; j < numThings; j++) {
var foo = doc.Whatever[i].Things[j].something;
// do some work
}
...
Enquiring minds want to know!
PS: The examples above are elided from real code. This should go without saying, but there’s a lot of other cruft in between the lines shown here. The code does actually do something! 😅