DEV Community

Cover image for Destructuring of Array
Muhammad    Uzair
Muhammad Uzair

Posted on

Destructuring of Array

Concept
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays.It is an elegant way to extract data from arrays.

    var array = ["My","Name","IS","Uzair"]
    console.log(array); //result ==>  ["My","Name","IS","Uzair"]

name1 will be assigned by My & name2 will be with Name

    var [name1,name2] = ["My","Name","IS","Uzair"]   
    console.log(name1);//result ==> My
    console.log(name2);//result ==> Name

( ,)comma is used skip one element every time

    //name3 will be assigned by Is $ name4 will be with Uzair
    var [,,name3,name4] = ["My","Name","IS","Uzair"]
    console.log(name3);//result ==> IS
    console.log(name4);//result ==> Uzair

( ... ) spread operator(three dots) unpack the string and this will be assinged like a array
here name5 will be My and newArray will be the new array containing remaining elements

    var [name5,...newArray] = ["My","Name","IS","Uzair"]
    console.log(newArray);//result==> ["Name","IS","Uzair"]
    console.log(name5);// result==> My

Hope you find this article useful. Please share your thoughts in the comment section.

Top comments (2)

Collapse
 
upieez profile image
Samuel Huang

Awesome I love your explanation. Clear and to the point

Collapse
 
uzairsamad profile image
Muhammad Uzair

Thank you very much for your consideration.