Home >Web Front-end >JS Tutorial >Why Does ES6 Array Destructuring with No Semicolons Exhibit Irregular Behavior?

Why Does ES6 Array Destructuring with No Semicolons Exhibit Irregular Behavior?

DDD
DDDOriginal
2024-10-24 06:23:30562browse

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>
  • [a, b] = …; is the conventional destructuring assignment.
  • (…) = ['BB', 'C'] is an assignment expression that evaluates to the array.
  • ['A', 'B'][…] is a property reference on an array literal.
  • (b, c) utilizes the comma operator, resulting in c (which is undefined).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Introduction to NodeJSNext article:Introduction to NodeJS