Javascript variable declaration with parentheses around initialized variables

React native website has the following line of code:

var React = require('react-native');
var { TabBarIOS, NavigatorIOS } = React;

      

In the second line of the example, what is the meaning of the parentheses around the TabBarIOS and NavigatorIOS variables?

+3


source to share


1 answer


This is called a destructuring assignment. This is a new feature introduced in the ECMAScript 6 specification.

Here's an example of an object:

var test = {
  "hello": 1,
  "world": 2
}

      

If we deconstruct it like this:

var {hello, world} = test;

      

This is equivalent to doing:

var hello = test.hello,
    world = test.world;

      


But, there are funnier things you can do with destructuring assignments ...



Let's assume we have this object:

var bucket = {
  ExampleObject: function(input){
    this.input = input.trim();
    return this.input;
  },

  TestingObject: function(example){
    this.example = example || {};
    console.log(this.example.input);
  }
}

      

Just for the record, I gave the members annoying names ... So when we destroy, we can rename them like this:

var {ExampleObject: Example, TestingObject: Test} = bucket;

      

The binding sample follows the syntax:

{ObjectMemberName}
// Or
{ObjectMemberName: VariableName}

      


For more information you can look at the draft ECMAScript 6 specification or MDN Documentation

+6


source







All Articles