2

I have met the following questions in JavaScript:

const [x1, ...[result]] = [3, 4, 5]
console.log([result])

I know x1 is 3, but why is the logging result [4] instead of [4,5]?

1
  • 4
    result is 4, not [ 4 ]. [ result ] can never be [ 4, 5 ]. It seems to behave similarly to const [first] = array;; in this case, it seems to be spreading the rest of [ 3, 4, 5 ], i.e. [ 4, 5 ] into ...[result], then destructuring [ 4, 5 ] into [ result ]; therefore result is 4. Commented Aug 11, 2021 at 14:28

1 Answer 1

5

So basically what is happening if we follow this syntax

const [a,...b] = [3,4,5]

Javascript creates an array called b and has the value [4,5]

But in your case what is happening is,

const [a,...[b]] = [3,4,5]

This is essentially assigning to only the first variable of the empty array with first value as b, which always equals 4 and not [4,5] as you expect.

So it's equivalent to the case below

const [a,...[b,c]] = [3,4,5]

the only difference is that you are not providing a variable c in your case. So b would correspond to 4 and c would correspond to 5

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

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.