Rohit Rohit - 2 months ago 20
Javascript Question

Understanding Export a round bracket function in ES6

I am trying to understand following export statement:

export default (
<Route path="/" component={App}>
<IndexRoute component={HomePage} />
<Route path="about" component={AboutPage}/>
</Route>
);


By definition, The export statement is used to export functions, objects, or primitive values.

Different Syntax:


export { name1, name2, …, nameN };
export { variable1 as name1, variable2 as name2, …, nameN };
export let name1, name2, …, nameN; // also var, function
export let name1 = …, name2 = …, …, nameN; // also var, const

export default expression;
export default function (…) { … } // also class, function*
export default function name1(…) { … } // also class, function*
export { name1 as default, … };

export * from …;
export { name1, name2, …, nameN } from …;
export { import1 as name1, import2 as name2, …, nameN } from …;



Among all of possible alternatives I am not able to relate how export default ( .. ); fit in.

I am guessing it would be exporting an anonymous function.

Answer Source

This rule applies:

export default expression;

(...) is the grouping operator, which is an expression. It simply evaluates to the result of the expression it contains. You surely have seen it before. For example:

(20 + 1) * 2

Some constructs require an expression to be started on the same line. In the following example, the function returns undefined, because the expression has to start in the same line as the return:

function foo() {
  return
    21 + 1;
}

console.log(foo());

With the grouping operator, we can do exactly that: Start the expression on the same line, but put the main part on the next line, for stylistic reasons:

function foo() {
  return (
    21 + 1
  );
}

console.log(foo());


I don't know whether or not using the grouping operator is required in the export default case, but it would be trivial to find out (run the code with and without it).

Even if it is not required, it doesn't change the result of the expression. Sometimes it's just used to be more visually pleasing or easier to read.