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

ES6 Array Destructuring Anomaly: Why Are Semicolons Important?

Linda Hamilton
Release: 2024-10-24 06:04:02
Original
434 people have browsed it

ES6 Array Destructuring Anomaly: Why Are Semicolons Important?

ES6 Array Destructuring Anomaly

In ES6, array destructuring allows for convenient assignment of array elements to variables. However, an unexpected behavior occurs when destructuring without proper use of semicolons.

Consider the following code:

<code class="js">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 Output:

  • a=A b=BB c=C

Actual Output:

  • a=BB b=C c=undefined

Explanation

The unexpected behavior arises from the absence of semicolons between the two destructuring statements. In ES6, semicolons are not automatically inserted. Therefore, the code is parsed as one large statement:

<code class="js">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

In this statement, the comma operator evaluates to the last expression in the parenthesis, which is the assignment of the array ['BB', 'C'] to the left-hand side (b, c). As a result, b receives 'BB' and c receives 'C'.

However, the second destructuring assignment is incorrectly assigned to the empty array literal ([]) instead of the array ['BB', 'C']. This is because the array literal is enclosed in parentheses without a semicolon at the start of the line.

To resolve this issue, use semicolons to separate the individual assignments:

<code class="js">let a, b, c;
[a, b] = ['A', 'B'];
[b, c] = ['BB', 'C'];
console.log(`a=${a} b=${b} c=${c}`);</code>
Copy after login

With the proper use of semicolons, the expected output is obtained.

The above is the detailed content of ES6 Array Destructuring Anomaly: Why Are Semicolons Important?. 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
Latest Articles by Author
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!