Search code examples
javascriptreactjsecmascript-6destructuring

What does the es6 { [a]: b } destructuring mean?


There is some destructuring going on here:

const { [a]: b } = this.props

But, what does [a]: b do: what does the brackets with colon do? In my case, a is supplied as one of the props with a string value.


Solution

  • [a] is a computed property name

    ...allows you to put an expression in brackets [], that will be computed and used as the property name


    { [a]: b } is a destructuring assignment with assigning to new variable names using a computed property name

    A property can be unpacked from an object and assigned to a variable with a different name than the object property


    Thus you end up with having a variable b in current scope that holds the value of this.props[a]

    Example

    this.props = {foo : 1, bar: 2};
    
    let p1 = 'foo';
    let p2 = 'bar';
    
    let { [p1]: b } = this.props;
    
    console.log(b); // 1
    
    let { [p2]: c } = this.props;
    
    console.log(c); // 2