Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring assignment in JavaScript

As can be seen in the Mozilla changlog for JavaScript 1.7 they have added destructuring assignment. Sadly I'm not very fond of the syntax (why write a and b twice?):

var a, b;  
[a, b] = f();

Something like this would have been a lot better:

var [a, b] = f();

That would still be backwards compatible. Python-like destructuring would not be backwards compatible.

Anyway the best solution for JavaScript 1.5 that I have been able to come up with is:

function assign(array, map) {
    var o = Object();
    var i = 0;
    $.each(map, function(e, _) {
        o[e] = array[i++];
    });
    return o;
}

Which works like:

var array = [1,2];
var _ = assign[array, { var1: null, var2: null });
_.var1; // prints 1
_.var2; // prints 2

But this really sucks because _ has no meaning. It's just an empty shell to store the names. But sadly it's needed because JavaScript doesn't have pointers. On the plus side you can assign default values in the case the values are not matched. Also note that this solution doesn't try to slice the array. So you can't do something like {first: 0, rest: 0}. But that could easily be done, if one wanted that behavior.

What is a better solution?

like image 418
Anders Rune Jensen Avatar asked Oct 15 '08 11:10

Anders Rune Jensen


People also ask

What is Destructuring assignment in JavaScript?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

How do you Destructure data in JavaScript?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element. const [var1, var2, ...]

Can you Destructure a function in JavaScript?

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that's more convenient. Destructuring also works great with complex functions that have a lot of parameters, default values, and so on.


2 Answers

First off, var [a, b] = f() works just fine in JavaScript 1.7 - try it!

Second, you can smooth out the usage syntax slightly using with():

var array = [1,2];
with (assign(array, { var1: null, var2: null }))
{
   var1; // == 1
   var2; // == 2
}

Of course, this won't allow you to modify the values of existing variables, so IMHO it's a whole lot less useful than the JavaScript 1.7 feature. In code I'm writing now, I just return objects directly and reference their members - I'll wait for the 1.7 features to become more widely available.

like image 70
Shog9 Avatar answered Oct 31 '22 10:10

Shog9


You don't need the dummy "_" variable. You can directly create "global" variables by using the window object scope:

window["foo"] = "bar";
alert(foo); // Gives "bar"

Here are few more points:

  • I wouldn't name this function "assign" because that's too generic a term.
  • To more closely resemble JS 1.7 syntax, I'd make the function take the destination as the first argument and the source as the second argument.
  • Using an object literal to pass the destination variables is cool but can be confused with JS 1.7 destructuring where the destination is actually an object and not an array. I prefer just using a comma delimited list of variable names as a string.

Here's what I came up with:

function destructure(dest, src) {  
    dest = dest.split(",");  

    for (var i = 0; i < src.length; i++) {  
        window[dest[i]] = src[i];  
    }  
}  

var arr = [42, 66];  

destructure("var1,var2", arr); 

alert(var1); // Gives 42
alert(var2); // Gives 66
like image 36
Ates Goral Avatar answered Oct 31 '22 09:10

Ates Goral