Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange syntax in javascript

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!

like image 301
julio Avatar asked Nov 30 '11 19:11

julio


People also ask

What are syntax errors in JavaScript?

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.

What does '$' mean in JavaScript?

$ 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).

What does 3 dots mean in JS?

(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.

Is JavaScript a messy language?

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.


2 Answers

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().

like image 66
Mike Christensen Avatar answered Oct 12 '22 14:10

Mike Christensen


[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"]
like image 33
Joe Avatar answered Oct 12 '22 14:10

Joe