Bond - 1 year ago 89

Javascript Question

I was checking out node.green and under **destructuring, assignment** > **nested rest**, the following example function is used:

`function f() {`

var a = [1, 2, 3], first, last;

[first, ...[a[2], last]] = a;

return first === 1 && last === 3 && (a + "") === "1,2,2";

}

console.log(f())

Now, I understand destructuring but I cannot figure out why how

`a`

`[1, 2, 2]`

Also

`[...[a[2], last]] = a;`

`[1, 2, 1]`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

```
[first, a[2], last] = a;
```

is like

```
// first == undefined, last == undefined, a == [1,2,3]
first = a[0];
// first == 1, last == undefined, a == [1,2,3]
a[2] = a[1];
// first == 1, last == undefined, a == [1,2,2]
last = a[2];
// first == 1, last == 2, a == [1,2,2]
```

```
[first, ...[a[2], last]] = a;
```

is like

```
// first == undefined, last == undefined, a == [1,2,3], tmp == undefined
first = a[0];
// first == 1, last == undefined, a == [1,2,3], tmp == undefined
tmp = [a[1], a[2]];
// first == 1, last == undefined, a == [1,2,3], tmp == [2,3]
a[2] = tmp[0];
// first == 1, last == undefined, a == [1,2,2], tmp == [2,3]
last = tmp[1];
// first == 1, last == 3, a == [1,2,2], tmp == [2,3]
```

```
[...[a[2], last]] = a;
```

is like

```
// last == undefined, a == [1,2,3], tmp == undefined
tmp = [a[0], a[1]];
// last == undefined, a == [1,2,3], tmp == [1,2]
a[2] = tmp[0];
// last == undefined, a == [1,2,1], tmp == [1,2]
last = tmp[1];
// last == 2, a == [1,2,1], tmp == [1,2]
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**