3

I have the following pieces of code (which only parses and runs correctly in Firefox)

var {A: a} = {A: 1};
console.log(a); // 1

And now we have a variable called 'a' with value is 1

So I have 3 questions to ask

  1. Why do we need 'var' here? Why don't we need var on the rhs of '='
  2. How does 'a' be in the scope ?
  3. How does 'a' get assigned to 1?
    it seems uses member-wise copy here, but why?
    shouldn't the object on the lhs will reference to the object on rhs?

For example,

var b = {B: 1};
var c = {B: 2};
b = c;
b.B = 3;
console.log(c);

In this assignment(b = c), b now references to c, and they share the same object. Why this assignment differs from my original one?

Forgot to mention I am testing on Firefox 16.0

Sirko
  • 65,767
  • 19
  • 135
  • 167
allstars.chh
  • 89
  • 1
  • 7

1 Answers1

3

The code that you have:

var {A: a} = {A: 1};

Is not valid JavaScript, it will only work when using Firefox and it does not pass any known linters).

As ThiefMaster mentions and after looking this up in the documentation, this usage is called destructuring assignment.

You can read about it here: Destructuring Assignment

Taken from the page.

You can use destructuring assignment, for example, to swap values:

var a = 1;
var b = 3;

[a, b] = [b, a];
Layke
  • 45,997
  • 10
  • 79
  • 109