Array destructuring assignment to exchange two values cannot be implemented without using a semicolon (;)
P粉714780768
2023-08-10 14:21:03
<p><br /></p>
<pre class="brush:php;toolbar:false;">let [x, y] = [10, 20] [y, x] = [x, y] console.log(x, y)< /pre>
<p>It didn't work as expected and gave me an error...</p>
<blockquote>
<p>Uncaught ReferenceError: Cannot access 'y' before initialization</p>
</blockquote>
<pre class="brush:php;toolbar:false;">let [x, y] = [10, 20]; // Use semicolon here [y, x] = [x, y] console. log(x, y)</pre>
<p>Now it works fine, can anyone please explain why it works now...</p>
First you need to declare x and y first, and you need to use a semicolon after the statement in a line.
let x, y; [x, y] = [10, 20]; [y, x] = [x, y]; console.log(x, y)
EDIT: Sorry, you don't need to declare them beforehand, but use semicolons to separate the directives.