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.
2
Answers
You are not destructuring.
Declares 3 variables and assigns a value to one of them. The line above is identical to:
This syntax allows you to declare (and optionally assign) several variables in a single statement, e.g.
Unassigned variables are default-initialized to
undefined
.In Javascript,
defines the variables b, c, and d. It also initializes d with the value of a, or the array [1, 2, 3] but leaves b and c uninitialized.
When you try to print the values of uninitialized variables to the console in Javascript, it prints
undefined
to signify the lack of any value.