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

What is happening when you're destructing an array without using square brackets?

Python developer here. I am using JavaScript to run the following command,

let a = [1, 2, 3];
let b , c, d = a;
console.log(b);
console.log(c);
console.log(d);

To my surprise, b and c are undefined while d is the entire a variable. I later realize that I am meant to go let [b, c, d] = a;, however I am just trying to understand what is happening and why they’re undefined.

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

>Solution :

You are not destructuring.

let b , c, d = a;

Declares 3 variables and assigns a value to one of them. The line above is identical to:

let b;
let c;
let d = a;

This syntax allows you to declare (and optionally assign) several variables in a single statement, e.g.

let tmp, x = 4, i, y = 2, z = x * 10 + y;

Unassigned variables are default-initialized to undefined.

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