"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > ES6 Array Destructuring: Why Doesn\'t It Work As Expected?

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

Published on 2024-11-06
Browse:688

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:

let a, b, c
[a, b] = ['A', 'B']
[b, c] = ['BB', 'C']
console.log(`a=${a} b=${b} c=${c}`)

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:

let a = undefined, b = undefined, c = undefined;
[a, b] = (['A', 'B']
[(b, c)] = ['BB', 'C']);
console.log(`a=${a} b=${b} c=${c}`);

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.

Release Statement This article is reprinted at: 1729721303 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3