Reputation: 33
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"?
Upvotes: 2
Views: 52
Reputation: 370679
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.
Upvotes: 2