Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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]];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading