Home >Web Front-end >JS Tutorial >Why Does ES6 Array Destructuring with No Semicolons Exhibit Irregular Behavior?
ES6 Array Destructuring Irregularity
An interesting anomaly occurs when employing ES6 array destructuring as demonstrated in the following code snippet:
<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
Analysis:
The root cause lies in the absence of semicolons, which is enabled by the automatic semicolon insertion (ASI) feature in JavaScript. However, in this specific case, ASI does not insert semicolons in the manner one might expect.
The code is logically dissected as follows:
<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>
Resolution:
To bypass this peculiarity, it is crucial to explicitly add semicolons at the initiation of every line that commences with (, [, /, , -, or `. This approach ensures proper separation of statements and eliminates the unexpected behavior.
The above is the detailed content of Why Does ES6 Array Destructuring with No Semicolons Exhibit Irregular Behavior?. For more information, please follow other related articles on the PHP Chinese website!