Your code and the original code do quite different things.
Assuming sheets
has objects in it that return the names "sheet1"
, "sheet2"
, and "sheet3"
from getName
, the original code creates an array that looks like this:
[
(missing),
["sheet1"],
["sheet2"],
["sheet3"]
]
Note two things:
- There is no entry at index 0. (It literally doesn't exist at all, which is subtly different from existing and containing the value
undefined
.)
- The other entries are single-element arrays, each containing its sheet name.
Your code creates this instead:
[
"sheet1",
"sheet2",
"sheet3"
]
Presumably the author had a reason for skipping index 0 and creating subordinate arrays (I'd guess because they were passing that result array into some API function that expects something in that form).
So there's no really a "better" or "worse" here, just different.
If your fundamental question is whether this:
var original = ["one", "two", "three"];
var updated = [];
for (var i = 0; i < original.length; ++i) {
updated[i] = original[i].toUpperCase(); // Or whatever
}
is better/worse than this:
var original = ["one", "two", "three"];
var updated = [];
for (var i = 0; i < original.length; ++i) {
updated.push(original[i].toUpperCase()); // Or whatever
}
the answer is: It's really a matter of style. Performance isn't markedly different between the two (and rarely matters), and amusingly one way is faster on some JavaScript engines and the other way is faster on others.
Both of those can probably be better expressed using map
:
var original = ["one", "two", "three"];
var updated = original.map(function(entry) { return entry.toUpperCase(); });
I think Google Sheets has map
, even though it mostly has only ES3-level features otherwise.
Side note: new Array
is almost never the right way to create an array.