skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. In Javascript,

    let b, c, d = a;
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search