js strange behavior Array Destructuring

郑郑少秋

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"?

CertainPerformance

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related