Search code examples
javascriptarraysdestructuring

Cannot access 'y' before initialization javascript


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


Solution

  • semicolons are missing

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