Search code examples
javascriptarraysdestructuring

What is an example of "array destructuring" via "assignment pattern" in JavaScript?


This MDN documentation on destructuring assignment says that "for both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern". Therefore, there should be four types of destructuring syntax:

  • Type 1: object destructuring via binding pattern
  • Type 2: array destructuring via binding pattern
  • Type 3: object destructuring via assignment pattern
  • Type 4: array destructuring via assignment pattern

I have read through the MDN documentation page many times, and the page seems to have provided examples only for the first 3 types. Googling doesn't seem to help either.

What would be an example of Type 4?

Thanks!

Update 1:

For Type 3, MDN provided this example:

// This assigns a to numbers[0] , and b to number[1] 
({ a: numbers[0], b: numbers[1] } = obj);  

What would be an equivalent example for Type 4? Thanks!


Solution

  • MDN should have explained Type 4 with a clearer and simpler example. Here you go:

    const source = [1, 2, 3];
    const target = [4, 5];
    
    [target[0], target[1]] = source; // target = [1, 2]
    

    Also, JavaScript arrays are just objects with indexed properties, so the above can also be written as the Type 3 format below:

    ({ 0: target[0], 1: target[1] } = source);