In ES6, array destructuring provides a concise syntax for extracting and assigning values from arrays. However, certain constructs can lead to unexpected results.
The provided code snippet raises the question:
Why does this code result in unexpected values after array destructuring?
<code class="javascript">let a, b, c; [a, b] = ['A', 'B']; [b, c] = ['BB', 'C']; console.log(`a=${a} b=${b} c=${c}`);</code>
Expected: a=A, b=BB, c=C
Actual: a=BB, b=C, c=undefined
Answer:
The issue lies in an omission of semicolons, which would normally separate these lines as distinct statements. Without semicolons, the code is parsed as a single statement and evaluated in a different order:
<code class="javascript">let a = undefined, b = undefined, c = undefined; [a, b] = (['A', 'B'] [(b, c)] = ['BB', 'C']); console.log(`a=${a} b=${b} c=${c}`);</code>
To avoid such misinterpretations and ensure correct evaluation, it is essential to explicitly include semicolons at the start of every line that begins with (, [, /, , -, or `.
The above is the detailed content of Why Does Array Destructuring Result in Unexpected Values in ES6?. For more information, please follow other related articles on the PHP Chinese website!