Home  >  Q&A  >  body text

Array destructuring assignment to exchange two values ​​cannot be implemented without using a semicolon (;)

<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>
P粉714780768P粉714780768437 days ago424

reply all(1)I'll reply

  • P粉212971745

    P粉2129717452023-08-11 12:51:28

    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.

    reply
    0
  • Cancelreply