Skip to content

JavaScript destructuring Array

  • by

JavaScript destructuring Array means extracting multiple properties from an array by taking the structure and deconstructing it down into its own constituent parts through assignments. It can be used for assignments and declaration of a variable.

var [first, second, third] = ["1", "2", "3"]; // = array

JavaScript destructuring array

Simple example code understands the array the left-hand side of the destructuring assignment is for defining what values are required to unpack from sourced variable.

<!DOCTYPE html>
<html>
<body>
  <script>
   var colors = ["Red", "White", "Blue", "Green", "Yellow", "Orange", "Pink"];  

    // destructuring assignment  
    var[color1, color2, color3] = colors;  

    console.log(color1); 
    console.log(color2); 
    console.log(color3);  

  </script>
</body>
</html>

Output:

JavaScript destructuring Array

Array destructuring and Rest operator

By using the rest operator (…) in array destructuring, you can put all the remaining elements of an array in a new array.

<script>
   var colors = ["Red", "White", "Blue", "Green", "Yellow", "Orange", "Pink"];
  
    var [a,b,...args] = colors;  

    console.log(a); // Red
    console.log(b); // White
    console.log(args);// [ "Blue", "Green", "Yellow", "Orange", "Pink" ]
</script>

Default values

var x, y;  
      
[x=50, y=70] = [100];  
console.log(x); // 100  
console.log(y); // 70  

Do comment if you have any doubts or suggestions on this Js Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *