Home > Web Front-end > JS Tutorial > body text

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

DDD
Release: 2024-10-24 06:23:30
Original
483 people have browsed it

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>
Copy after login

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>
Copy after login
  • [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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!