Cannot access array before initilaisation during swap

Ive come to something strange

Im trying to swap the array value 0 with the array value 1

Ive found a previous post stating that this is possible

[arr[0], arr[1]] = [arr[1], arr[0]];

So I wanted to replicate that

let array_names = ["Dave", "johson", "Lime", "Key", "Freeman", "Chell", "Shepart", "Furious"]
[array_names[0], array_names[1]] = [array_names[1], array_names[0]]

However something strange happens

I get an error message stating that

ReferenceError: Cannot access 'array_names' before initialization

I have checked and there isnt a typo anywhere

Also yes I did initialize the array before doing any modificiation

>Solution :

Your code is totally correct, but due to a missing semicolon, the interpreter parsed your code differently..

let array_names = ["Dave", "johson", "Lime", "Key", "Freeman", "Chell", "Shepart", "Furious"]
[array_names[0], array_names[1]] = [array_names[1], array_names[0]]

The expression was evaluated as

["Dave", "johson", ...][array_names[0], array_names[1]] 

The code is parsed as one line statement.

The right answer as stated by Shubhada is

let array_names = ["Dave", "johson", "Lime", "Key", "Freeman", "Chell", "Shepart", "Furious"]; //Terminate statement
[array_names[0], array_names[1]] = [array_names[1], array_names[0]];

Leave a Reply