2

const test = () => {
  const arr = [1, 2]
  console.log("any strings") // focus on this line
  [arr[0], arr[1]] = [arr[1], arr[0]]
}

const test1 = () => {
  const arr = [1, 2]
  console.log("any strings"); // add a semicolon will works or comment this line will works too
  [arr[0], arr[1]] = [arr[1], arr[0]]
}

test() // error

test1() // works

Why does the first function test throw error "Cannot set property '2' of undefined"?

1

1 Answer 1

2

The issue here doesn't have anything to do with destructuring. In the first snippet, because the second line after console.log begins with an opening bracket, it considers the lines as part of the same statement.

console.log("any strings")[arr[0], arr[1]]

Note that in bracket notation, [arr[0], arr[1]] will resolve to [arr[1]] - that's the comma operator. So, it's attempting to assign to the [arr[1]] = [2] property of the result of calling console.log("any strings"). To the interpreter, it's identical to this snippet:

const test = () => {
    const arr = [1,2]
    console.log("any strings")[arr[0], arr[1]]
      = [arr[1], arr[0]]    
} 

test()

Same as:

const test = () => {
    const arr = [1,2]
    console.log("any strings")[arr[1]]
      = [arr[1], arr[0]]    
} 

test()

Of course, console.log returns undefined; it has no such property [2]. Always use semicolons when in doubt.

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.