4

In some js library I found this code snippet:

var start, end, sel, scrollPos, subst;

[start, end, scrollPos, sel] = getSelection();

Imo this is not valid assignment but code seems to be working. Can you help?

EDIT:

longer version:

...
var start, end, sel, scrollPos, subst;
        if (typeof(document["selection"]) != "undefined") {
            sel = document.selection.createRange().text;
        } else if (typeof(textarea["setSelectionRange"]) != "undefined") {
            [start, end, scrollPos, sel] = getSelection();
        }
...
Entity Black
  • 3,401
  • 2
  • 23
  • 38

1 Answers1

5

This appears to be a JS 1.7 feature called "Destructuring Assignment"

Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

The object and array literal expressions provide an easy way to create ad-hoc packages of data. Once you've created these packages of data, you can use them any way you want to. You can even return them from functions.

One particularly useful thing you can do with destructuring assignment is to read an entire structure in a single statement, although there are a number of interesting things you can do with them, as shown in the section full of examples that follows.

This capability is similar to features present in languages such as Perl and Python.

...farther down the page:

You can use destructuring assignment, for example, to swap values:

var a = 1;
var b = 3;
[a, b] = [b, a];

As far as using the feature, it appears to only be supported by Mozilla Firefox, which means it's perfectly acceptable to use it so long as you're only supporting that browser. Browser plugins, for example, can be written to take advantage of this feature.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367