I'm working on debugging some code someone else wrote (using Mootools as the base library), and I came across this function:
[note, $H(options.text).getKeys()].flatten().each(function(option){
// bunch of stuff happening
});
I've never seen this syntax before, with the brackets and the $H notation (eg. [note, $H(options.text).getKeys()]
). Can anyone explain how that works or point me to a reference on it?
Thanks!
An exception caused by the incorrect use of a pre-defined syntax. Syntax errors are detected while compiling or parsing source code. For example, if you leave off a closing brace ( } ) when defining a JavaScript function, you trigger a syntax error.
$ is simply a valid JavaScript identifier. JavaScript allows upper and lower letters, numbers, and $ and _ . The $ was intended to be used for machine-generated variables (such as $0001 ). Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function).
(three dots in JavaScript) is called the Spread Syntax or Spread Operator. This allows an iterable such as an array expression or string to be expanded or an object expression to be expanded wherever placed.
The syntax can feel messy if you're trying to do things in a synchronous way, which is how almost all other programming languages guide you to breaking apart problems. Once you get familiar with the syntax of JavaScript and you get good at thinking about things in that way, JavaScript will feel much more natural.
This basically aggregates two arrays together. Take, for example, this code:
var a = [1,2,3];
var b = [4,5,6];
var c = [a, b].flatten();
alert(c);
The arrays [1,2,3]
and [4,5,6]
are combined (or "flattened") into a single array, 1,2,3,4,5,6
.
In your code:
[note, $H(options.text).getKeys()].flatten()
note
(perhaps another array) and whatever getKeys()
returns are flattened into a single array. Then, a function is performed across each element.
Update:
The $H function is a utility function in Mootools that is a shortcut for Hash().
[note, $H(options.text).getKeys()]
is most likely becoming:
[note, ["string1", "string2"]]
so it returns an array. So ["whatever note is", ["Another array", "of objects"]]
needs to be flattened to:
["whatever note is", "Another array", "of objects"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With