1

import:

import React, { Component } from 'react';

Destructuring:

let z, {b} = {a: 1, b: 2, c: 3}

it looks that they follow same syntax.

but in second one, z will be undefined instead of {a: 1, b: 2, c: 3}.

so import syntax is different than es6 Destructuring? How their syntax are related to each other?

yaya
  • 7,675
  • 1
  • 39
  • 38
  • 2
    Technically, they aren't. They are two different pieces of syntax but they look similar in some cases. Mostly for ease of use, as they sort of work similarly - if you have `{x } = y` or `import {x} from y` in both cases you want one thing from the right identifier. If the syntax was completely different it'd be more confusing. – VLAZ Jul 31 '20 at 22:17
  • @VLAZ thanks, so they are two different syntax, but desined to looks similar for ease of use and not confussion? i think that's the answer i was looking for and it'll be good if you submit it as an answer. – yaya Jul 31 '20 at 22:22
  • 2
    Maybe of interest: [Destructuring a default export object](https://stackoverflow.com/q/43814830/1048572), [Why does JavaScript have default exports?](https://stackoverflow.com/a/57021113/1048572) – Bergi Jul 31 '20 at 22:33

1 Answers1

4

There is no relation at all. The full syntax for your import declaration is

import { default as React, Component as Component } from 'react';

while the full syntax for your destructuring variable declaration is

let z = undefined, { b: b } = {a: 1, b: 2, c: 3};

They do totally different things. Imports create aliases, destructuring patterns put values into targets (with optional default initialisers and nesting). That their shorthand forms are similar to each other is mostly coincidental, caused by both using braces. However, blocks do as well:

React; { Component } z; { b }

is valid JavaScript :-)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 2
    I think it's more planned than coincidental but if you mean "not meant to be interchangeable", I do agree with that. I suspect after TC39 designed one and came to design the other they borrowed some ideas. Or even more likely, the designs were running in parallel anyway with some of the same people between them. – VLAZ Jul 31 '20 at 22:25