Home  >  Article  >  Web Front-end  >  Why Does Array Destructuring Result in Unexpected Values in ES6?

Why Does Array Destructuring Result in Unexpected Values in ES6?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 06:06:30960browse

Why Does Array Destructuring Result in Unexpected Values in ES6?

Quirks of Array Destructuring in ES6

In ES6, array destructuring provides a concise syntax for extracting and assigning values from arrays. However, certain constructs can lead to unexpected results.

The provided code snippet raises the question:

Why does this code result in unexpected values after array destructuring?

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

Expected: a=A, b=BB, c=C

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

Answer:

The issue lies in an omission of semicolons, which would normally separate these lines as distinct statements. Without semicolons, the code is parsed as a single statement and evaluated in a different order:

<code class="javascript">let a = undefined, b = undefined, c = undefined;
[a, b] = (['A', 'B']
[(b, c)] = ['BB', 'C']);
console.log(`a=${a} b=${b} c=${c}`);</code>
  • [a, b] = …; is a destructuring assignment as expected.
  • (… = ['BB', 'C']) is an assignment expression that assigns the array to the left-hand side and evaluates to the array.
  • 'A', 'B' is a property reference on an array literal.
  • (b, c) is using the comma operator, evaluating to c (which is undefined).

To avoid such misinterpretations and ensure correct evaluation, it is essential to explicitly include semicolons at the start of every line that begins with (, [, /, , -, or `.

The above is the detailed content of Why Does Array Destructuring Result in Unexpected Values in ES6?. For more information, please follow other related articles on the PHP Chinese website!

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