-2

I am trying to swap values of two variables using array destructuring, however I get the error Cannot access 'y' before initialization. Can someone please explain why it is not working and provide a solution

my code :

    let x = 'bob'
    let y = 'john'
    
    [x, y]=[y, x]
    
    console.log(x, y)

error: Cannot access 'y' before initialization

ConnerWithAnE
  • 1,106
  • 10
  • 26
  • It is working as expected, Doesn't give me an error... [codepen](https://codepen.io/kumarmasterpraveen/pen/MWoYywL?editors=0011) – DecPK Aug 25 '21 at 01:51
  • 2
    Use semicolons. – Sebastian Simon Aug 25 '21 at 01:52
  • 2
    Does this answer your question? [What are the rules for JavaScript's automatic semicolon insertion (ASI)?](/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi) Also: [a javascript question about destructuring when `[a, b] = [b ,a]`](/q/56204661/4642212). – Sebastian Simon Aug 25 '21 at 01:52

1 Answers1

1

semicolons are missing

let x = 'bob';
let y = 'john';

[x, y]=[y, x];

console.log(x, y)
Saydur Rahman
  • 64
  • 2
  • 4