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

ES6 Array Destructuring: Why Doesn\'t It Work As Expected?

Susan Sarandon
Release: 2024-10-24 06:10:02
Original
797 people have browsed it

ES6 Array Destructuring: Why Doesn't It Work As Expected?

ES6 Array Destructuring: Unforeseen Behavior

In ES6, destructuring assignment for arrays can lead to unexpected results, leaving programmers puzzled. One such instance is illustrated by 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

Intended Output:
a=A b=BB c=C

Actual Output:
a=BB b=C c=undefined

Explanation:

Contrary to expectations, this code does not yield the desired output. Instead, it swaps the values of b and c, leaving c undefined. To understand why this happens, we need to examine the code closely.

Parsing and Evaluation:

In JavaScript, semicolons are optional to delimit statements. Without explicit semicolons, the code is parsed as a single 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

Breakdown of the Statement:

  • [a, b] = (['A', 'B'] is a destructuring assignment, similar to the one in the original code.
  • [(b, c)] = ['BB', 'C'] is an assignment expression that assigns the array ['BB', 'C'] to the left-hand operand. This expression evaluates to the same array.
  • ['A', 'B'][…] is a property reference on an array literal, which evaluates to undefined.
  • (b, c) uses the comma operator, which evaluates to the last operand (c), which is undefined.

Implications:

Therefore, the code assigns undefined to both a and c, while b correctly receives the value 'C'. To avoid this behavior, programmers should explicitly use semicolons or begin every line with an operator that requires a semicolon to be automatically inserted (e.g., (, [, /, , -, or `).

This understanding ensures that destructuring assignments in ES6 operate as expected, preventing unexpected value swaps and undefined assignments.

The above is the detailed content of ES6 Array Destructuring: Why Doesn\'t It Work As Expected?. 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!