Search code examples
javascriptarrayseslintdestructuring

Array destructuring in JavaScript


I have this code in my vue-js app:

methods: {
    onSubmit() {
      ApiService.post('auth/sign_in', {
        email: this.email,
        password: this.password,
      })
        .then((res) => {
          saveHeaderToCookie(res.headers);
          this.$router.push({ name: 'about' });
        })
        .catch((res) => {
          this.message = res.response.data.errors[0];
          this.msgStatus = true;
          this.msgType = 'error';
        });
    },
  }

While running Eslint I got an error saying "Use array destructuring" (prefer-destructuring) at this line:

this.message = res.response.data.errors[0];

What is array destructuring and how to do this? Please provide me a concept on this. I've researched it but could not figure it out.


Solution

  • Destucturing is using structure-like syntax on the left-hand-side of an assignment to assign elements of a structure on the right-hand-side to individual variables. For exampple,

    let array = [1, 2, 3, 4];
    let [first, _, third] = array;
    

    destructures the array [1, 2, 3] and assigns individual elements to first and third (_ being a placeholder, making it skip the second element). Because LHS is shorter than RHS, 4 is also being ignored. It is equivalent to:

    let first = array[0];
    let third = array[2];
    

    There is also an object destructuring assignment:

    let object = {first: 1, second: 2, third: 3, some: 4};
    let {first, third, fourth: some} = object;
    

    which is equivalent to

    let first = object.first;
    let third = object.third;
    let fourth = object.some;
    

    Spread operator is also permitted:

    let [first, ...rest] = [1, 2, 3];
    

    would assign 1 to first, and [2, 3] to rest.

    In your code, it says you could do this instead:

    [this.message] = res.response.data.errors;
    

    The documentation on prefer-destructuring lays out what it considers to be "correct".