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:
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.
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