2

Noticed an interesting behavior of Javascript while playing with Array Destructuring eg:

let a = [1, 2, 3];
let b = [one, two, three, four = 4] = a

console.log(one, two, three, four)
console.log(b)

When I say a.length output is 3
If I say b.length output is 3.
However, if I say four output is 4.
If four is an element of b then why b.length is shown as 3 why not as 4?

3
  • 2
    Because you set b to a, which is [1,2,3] (len 3) Commented Nov 13, 2019 at 10:50
  • Thanks @Dino for your instant reply. Yes, I got that part, however, As I have added one more additional element in variable b and when I am accessing it, it is giving me a correct output. That's why bit confused, when its holding the value then why its not showing it correctly when we say b.length. Commented Nov 13, 2019 at 10:56
  • the construct a = b = c is equivalent to b=c, a=c not b=c, a=b. This means in your case [one, two, three, four=4] = a; let b = a; Commented Nov 13, 2019 at 11:38

3 Answers 3

2

this let b = [one, two, three, four=4] = a does not create a new array with four elements to assign to b.

if you do let b = [one, two] = a, you would still get b.length 3 because it assigns the value a to b without any modification.

remember, you're simply using de-structuring and default assignment feature in here -> [one, two, three, four=4] which does not create a new array.

if you do a === b, you will get true.

Sign up to request clarification or add additional context in comments.

Comments

2

four is not an element of b (which is a). You're using the default value =4 feature there; it's not getting assigned into b.

Running your code through the Babel REPL, to de-sugar that destructuring, gives us something like:

var _a, _a$;

var a = [1, 2, 3];
_a = a;
one = _a[0];
two = _a[1];
three = _a[2];
_a$ = _a[3];
four = _a$ === void 0 ? 4 : _a$;
var b = _a;

As you can see, b eventually just gets assigned _a, which is a; the destructuring assignments occur "in-between".

Comments

1

Assignment works right-to-left, and when something is assigned to with = (whether by destructuring or not), the whole expression on the left and right of the = is equivalent to the value of what was assigned (on the right hand side).

There is no intermediate array with

[one, two, three, four=4] =

Rather, that's just assigning to existing variables, without creating an additional expression (other than 4, which is assigned to four).

a = [1,2,3];
let b = [one, two, three, four=4] = a

is like

a = [1,2,3];
let b = (() => {
  [one, two, three, four=4] = a;
  return a;
})()

In your code, b is the exact same array as a:

a = [1,2,3];
let b = [one, two, three, four=4] = a;

console.log(b === a);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.