What does curly brackets in the `var { … } = …` statements do?

What you’re looking at is a destructuring assignment. It’s a form of pattern matching like in Haskell.

Using destructuring assignment you can extract values from objects and arrays and assign them to newly declared variables using the object and array literal syntax. This makes code much more succinct.

For example:

var ascii = {
    a: 97,
    b: 98,
    c: 99
};

var {a, b, c} = ascii;

The above code is equivalent to:

var ascii = {
    a: 97,
    b: 98,
    c: 99
};

var a = ascii.a;
var b = ascii.b;
var c = ascii.c;

Similarly for arrays:

var ascii = [97, 98, 99];

var [a, b, c] = ascii;

This is equivalent to:

var ascii = [97, 98, 99];

var a = ascii[0];
var b = ascii[1];
var c = ascii[2];

You can also extract and rename an object property as follows:

var ascii = {
    a: 97,
    b: 98,
    c: 99
};

var {a: A, b: B, c: C} = ascii;

This is equivalent to:

var ascii = {
    a: 97,
    b: 98,
    c: 99
};

var A = ascii.a;
var B = ascii.b;
var C = ascii.c;

That’s all there is to it.

Leave a Comment