Home >Web Front-end >JS Tutorial >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>
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>
Breakdown of the Statement:
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!