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>
   var colors = ["Red", "White", "Blue", "Green", "Yellow", "Orange", "Pink"];  

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




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.

   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" ]

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading